﻿'Imports SFSPortal
Imports System.Drawing.Imaging
Imports System.IO
Imports System.IO.File
Imports System.Math
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Imports System.Windows.Forms.DataVisualization.Charting
Imports System.Xml
Imports Cognex.VisionPro
Imports Cognex.VisionPro.CalibFix
Imports Cognex.VisionPro.ID
Imports Cognex.VisionPro.PMAlign
Imports Cognex.VisionPro.ToolBlock
Imports Cognex.VisionPro.TwoDSymbol
Imports CommonDLL
Imports CommonDLL.Common
Imports CommonDLL.Common.SocketHelper
Imports HslCommunication
Imports HslCommunication.Profinet.Melsec

Public Class FrmMain
    Public bzw As Integer
    Dim portnum As Integer = 8
    Dim mServer(portnum - 1) As Socket
    Dim mServerBarcode(1) As Socket
    Dim mServerIOT(1) As Socket

    'Dim mServer2(1) As Socket
    'Dim IP As String = "10.0.20.225"
    Dim IP As String = "192.168.1.101"

    Dim Port As Integer = 8000
    Dim ReciveFlag As String = ""
    Dim SendDate As String = ""
    Dim SerialPortRecive As String = ""
    Dim Aleardate As String = ""
    Dim IsScrewFail As Boolean = False

    Public pointCAD(80) As Double
    Public pointCAD_X(35) As Double
    Public pointCAD_Y(35) As Double
    Public pointCAD_Z(35) As Double

    ' Public pointCAD_U(35) As Double
    Public photo_point(15) As Double

    Dim ReturnXYR As returnXY
    Public resu(72) As Double   'twopointurn 函数返回XY转数组 36个点
    Public temp(10) As Double
    Public pointCAD_C(30) As Double

    '是否是第一次发送数据，0不是，1是，程序刚启动时默认是第一次发送，此时IsRun=0
    Dim IsFirstSend As Integer = 1

    '设备是否运行，0停止，1运行
    Dim IsRun As Integer = 0

    Dim List1 As ArrayList = New ArrayList
    Dim List2 As ArrayList = New ArrayList
    '记录计时器PLClear调用的次数，每次一分钟，num=60的时候表示一个小时

    Private Declare Function SetParent Lib "user32" Alias "SetParent" (ByVal hWndChild As IntPtr, ByVal hWndNewParent As IntPtr) As Integer
    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
    Private Declare Function MoveWindow Lib "user32" (ByVal hwnd As Integer, ByVal x As Integer, ByVal y As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal bRepaint As Integer) As Integer
    Private Declare Function SetCursorPos Lib "User32" (ByVal x As Integer, ByVal y As Integer) As Boolean
    Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As IntPtr, ByVal wMsg As IntPtr, ByVal wParam As IntPtr, ByVal lParam As String) As IntPtr
    Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As IntPtr, ByVal hWnd2 As IntPtr, ByVal lpsz1 As String, ByVal lpsz2 As String) As IntPtr
    Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As IntPtr, ByVal wMsg As IntPtr, ByVal wParam As IntPtr, ByVal lParam As String) As IntPtr

    Private Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Integer, ByVal dx As Integer, ByVal dy As Integer, ByVal cButtons As Integer, ByVal dwExtraInfo As Integer)

    Delegate Sub AddRecvToText(ByVal strName As String)

    Public Const WM_CLOSE = &H10

    Dim BarcodeNG_count As Integer = 0
    Dim exeName As String = "C:\Program Files (x86)\PM Designer\V2.1\PanelSim.exe"
    Public MESheader(3, 1) As String

    Dim ProdInfoQueue As Queue(Of ProdInfo) = New Queue(Of ProdInfo) 'SN$ModeName$SrialNO$UnLockFlag$
    Dim SN_NULLflag As Boolean = False
    Dim Can_Barcode As Boolean = False

    Dim torqueTemp As Integer '保存已发的扭力值
    Public showSNQueueFlag As Boolean '显示SN队列

    Private Sub FrmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        GetXML()
        MESheader(0, 0) = "X-Auth-Meta"
        MESheader(0, 1) = "b5lftxujHRVm4/XipG0eRTi64s77LqgWJo/2YuJ/3luwTxddTzoVHHzSApOSQ1Om"

        MESheader(1, 0) = "X-FN"
        MESheader(1, 1) = "GET_WIPSN_BASEINFO"

        MESheader(2, 0) = "X-Request-Id"
        MESheader(2, 1) = "32e54911-d337-32d2-9a19-21f3a9f22a13" '32e54911-d337-32d2-9a19-21f3a9f22a13

        MESheader(3, 0) = "X-Time"
        MESheader(3, 1) = Format(DateTime.Now, "yyyy-MM-dd HH:mm:ss")

        Dim countP As Integer = 0
        For Each proce As Process In Process.GetProcesses()
            If proce.ProcessName = "LNLON" Or proce.ProcessName = "XCPro" Then
                countP += 1
                If countP > 1 Then
                    MessageBox.Show("已经一个实例的本程序正在运行。")
                    End
                End If

            End If
        Next
        Control.CheckForIllegalCrossThreadCalls = False
        TabControl1.SelectedIndex = 0
        Dim appwin As IntPtr
        Dim Pro As Process
        Try
            Pro = System.Diagnostics.Process.Start(exeName)
            Pro.WaitForInputIdle()
            appwin = Pro.MainWindowHandle
            System.Threading.Thread.Sleep(100)
        Catch ex As Exception
            MessageBox.Show(Me, ex.Message, "Error")
        End Try

        SetParent(appwin, Me.Panel1.Handle)
        MoveWindow(appwin, 0, 0, Me.Width, Me.Height, True)

        Control.CheckForIllegalCrossThreadCalls = False
        Me.FormBorderStyle = Windows.Forms.FormBorderStyle.None
        Me.WindowState = FormWindowState.Maximized

        EQ_Status = Equipment_Status._STARTUP
        'InitLog()

        InitMachineInfo()               '获取机台信息

        '初始化参数
        initParam()

        Me.Show()
        SetCursorPos(550, 280)
        mouse_event(&H2, 0, 0, 0, 0) '鼠标左键按下
        mouse_event(&H4, 0, 0, 0, 0) '鼠标左键弹起

        '初始化串口
        InitCom()

        '初始网络端口
        InitTcpSever()                    '网口1
        wait(50)

        InitBarcodeTcpSever()

        'Open_Click_PLC()
        If gCurrProName <> "" Then
            '初始化已设定好的工具
            initPro(gCurrProName)
        Else
            '初始化图像处理工具
            initTool()
        End If
        '初始化数据
        InitSetting()
        'InitTcpSever2()                   '网口2
        '网口2-参数设置中联机勾选
        If Upload_enable = False Then
            Button_LJ.Text = "关闭"
            Button_LJ.BackColor = Color.GreenYellow
        End If

        Init_plc("192.168.1.55", "1026")

        '初始化保养信息
        InitMaintanceInfo()

        '初始化完成后，权限管理启用
        gPriority = 0
        TextBox_OPID.Text = "未登陆"

        TextBox_OPID.BackColor = Color.WhiteSmoke
        FrmAdmin.EnableMenu()

        OpenUploadProcess()
        Look_screw_deleted() '''''''''''''删除过期锁付数据
        Open_time = Date.Now.Hour
        Timer_Log.Enabled = True
        Timer_ClearRichTextBoxlog.Enabled = True

        If Upload_enable = True Then
            InitTcpSever2()
        Else
            AppendInfoToTextBox("联机功能未打开")
            Button_LJ.Text = "关闭"
            Button_LJ.BackColor = Color.GreenYellow
        End If

        SoveProdLuck = False
        SoveProdCP = False
        LogRed = False
        TimerLckProd.Enabled = True
        Timerclear.Enabled = True
        TimerOPC.Enabled = True
        Dim th As Thread = New Thread(AddressOf Automaticlogout)
        th.IsBackground = True
        th.Start()
        '
        ConnectScan(PublicHikScanConfig.ScanIP, PublicHikScanConfig.ScanProt)
        Dim thr As Thread = New Thread(AddressOf SnedDataToScan)
        thr.IsBackground = True
        thr.Start()
        '
    End Sub

    Dim ScanClient As Socket

    Public Sub ConnectScan(ByVal ip As String, ByVal prot As String)
        Try
            ScanClient = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            ScanClient.Connect(ip, Convert.ToInt32(prot))
        Catch ex As Exception
            AppendInfoToTextBox(ex.Message)
        End Try

    End Sub

    Public Sub SnedDataToScan()
        While True
            Try
                If PublicHikScanConfig.ScanEnable Then
                    If PublicHikScanConfig.ScanWhileEnable Then
                        If ScanClient IsNot Nothing Then
                            ScanClient.Send(Encoding.ASCII.GetBytes(PublicHikScanConfig.ScanStart))
                        End If
                    End If
                End If
            Catch ex As Exception
                AppendInfoToTextBox(ex.Message)
                ScanClient = Nothing
                ConnectScan(PublicHikScanConfig.ScanIP, PublicHikScanConfig.ScanProt)
            End Try
            Thread.Sleep(Val(PublicHikScanConfig.ScanWhileTime))
        End While
    End Sub

    Public Sub InitLog()
        Dim LogFilePath As String = CD_Dir & "上位机资料" & "\log"
        Dim LogFileName As String = "System_Histroy_" & Format(DateTime.Now, "yyyyMMddHHmmss") & ".txt"
        log = New Common.LogHelper(LogFilePath, LogFileName, New Font("微软雅黑", 14))
    End Sub

    Private Function GetXML()
        Dim xmlpath As String = gProDataPath & "\Param.xml"
        If Exists(xmlpath) Then
            Dim xtr As XmlTextReader = New XmlTextReader(xmlpath)
            Try
                While xtr.Read()
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "FTPUploadPath" Then
                        FTPUploadPath1 = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "MySQLIP" Then
                        MySQLIP = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "MySQLUserName" Then
                        MySQLUserName = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "MySQLPwd" Then
                        MySQLPassWord = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "MySQLDB" Then
                        MySQLDataBase = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "MySQLIPRemote" Then
                        MySQLIPRemote = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "MySQLUserNameRemote" Then
                        MySQLUserNameRemote = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "MySQLPwdRemote" Then
                        MySQLPassWordRemote = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "MySQLDBRemote" Then
                        MySQLDataBaseRemote = xtr.ReadString()
                    End If
                End While
            Catch ex As Exception
                MsgBox("参数文件读取错误!" & vbCrLf & ex.Message.ToString)
            Finally
                xtr.Close()
            End Try
        End If
    End Function

    Public Sub InitMachineInfo()
        Dim xmlpath As String = Application.StartupPath & "\MachineInfo.xml"
        If Exists(xmlpath) Then
            Dim xtr As XmlTextReader = New XmlTextReader(xmlpath)
            Try
                While xtr.Read()
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "DeviceType" Then
                        machineInfo.Device_type = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "Manufacturer" Then
                        machineInfo.Manufacturer = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "DeviceCode" Then
                        machineInfo.Device_Code = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "DeviceId" Then
                        machineInfo.Device_id = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "Line" Then
                        machineInfo.Line = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "IP" Then
                        machineInfo.IP = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "Family" Then
                        machineInfo.Family = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "StateFre" Then
                        StateFreTime = xtr.ReadString()
                        'UploadStatus.Interval = StateFreTime * 1000

                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "ProductFre" Then
                        ProductFreTime = xtr.ReadString()
                        'UploadMainInfo.Interval = ProductFreTime * 1000

                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "IP_51" Then
                        machineInfo.IP_51 = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "MES_UploadAddress" Then
                        machineInfo.MES_UploadAddress = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "XEnv" Then
                        machineInfo.XEnv = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "Token" Then
                        machineInfo.Token = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "UserName" Then
                        machineInfo.UserName = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "SECTION" Then
                        machineInfo.SECTION = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "DirSwitchProd" Then
                        machineInfo.DirSwitchProd = xtr.ReadString()
                    End If
                    '
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "FirstCLearQuene" Then
                        machineInfo.FirstClearQuene = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "ClearQuene" Then
                        machineInfo.ClearQuene = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "ConfigMustLogin" Then
                        machineInfo.ConfigMustLogin = xtr.ReadString()
                    End If
                    '
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "ScanIP" Then
                        PublicHikScanConfig.ScanIP = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "ScanProt" Then
                        PublicHikScanConfig.ScanProt = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "ScanStart" Then
                        PublicHikScanConfig.ScanStart = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "ScanEnd" Then
                        PublicHikScanConfig.ScanEnd = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "ScanWhileTime" Then
                        PublicHikScanConfig.ScanWhileTime = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "ScanWhileEnable" Then
                        PublicHikScanConfig.ScanWhileEnable = IIf(xtr.ReadString() = "True", True, False)
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "ScanEnable" Then
                        PublicHikScanConfig.ScanEnable = IIf(xtr.ReadString() = "True", True, False)
                    End If
                    '
                End While

                machineInfoStatus.Device_type = machineInfo.Device_type
                machineInfoStatus.Manufacturer = machineInfo.Manufacturer
                machineInfoStatus.Device_Code = machineInfo.Device_Code
                machineInfoStatus.Device_id = machineInfo.Device_id
                machineInfoStatus.Line = machineInfo.Line
                machineInfoStatus.IP = machineInfo.IP

                mainInfo.Device_id = machineInfo.Device_id
                mainInfo.Line = machineInfo.Line

                SNInfo.Device_id = machineInfo.Device_id
                SNInfo.Line = machineInfo.Line
                SNInfo.Family = machineInfo.Family
            Catch ex As Exception
                MsgBox("设备信息文件错误!" & vbCrLf & ex.Message.ToString)
            Finally
                xtr.Close()
            End Try
        End If

        loadequipment()
    End Sub

    Public Sub loadequipment()
        Dim xmlpath1 As String = Application.StartupPath & "\EquipmentInfo.xml"
        If Exists(xmlpath1) Then
            Dim xtr As XmlTextReader = New XmlTextReader(xmlpath1)
            Try
                While xtr.Read()
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "Robot_Company" Then
                        EquipmentInfo.Robot_Company = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "Robot_Version" Then
                        EquipmentInfo.Robot_Version = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "Robot_Datatime" Then
                        EquipmentInfo.Robot_Datatime = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "Charge_Name" Then
                        EquipmentInfo.Charge_Name = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "Charge_Telephone" Then
                        EquipmentInfo.Charge_Telephone = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "Charge_Email" Then
                        EquipmentInfo.Charge_Email = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "OPCVersion" Then
                        EquipmentInfo.OPCVersion = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "SoftVersion" Then
                        EquipmentInfo.SoftVersion = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "MachineID" Then
                        EquipmentInfo.MachineID = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "LineID" Then
                        EquipmentInfo.LineID = xtr.ReadString()
                    End If
                    If xtr.NodeType = XmlNodeType.Element And xtr.LocalName = "StationID" Then
                        EquipmentInfo.StationID = xtr.ReadString()
                    End If
                End While
                xtr.Close()

                OPC_RefreshData_Info()
            Catch ex As Exception
                MsgBox("设备管理文件错误!" & vbCrLf & ex.Message.ToString)
                xtr.Close()
            Finally

            End Try
        End If
    End Sub

    Private Sub initParam() '初始化参数
        Try
            gIsRun = True
            TSGrabContinues1.Enabled = False
            'TSGrabContinues2.Enabled = False
            'TSGrabContinues3.Enabled = False
            'TSGrabContinues4.Enabled = False
            'TSIsRun.BackColor = Color.Green
            产品管理ProductToolStripMenuItem.Enabled = False
            设置ToolStripMenuItem.Enabled = False
            Count_Clear.Enabled = False

            ToolStripButton17.Enabled = False
            '  TestToolStripMenuItem.Enabled = False
            '   TxtScrewIndex1.ReadOnly = False
            gIsModBus = False
            gCurrProName = GetSetting("XCPro", "Settings", "当前产品", "") '当前产品
            gUserTime = GetSetting("XCPro", "Settings", "UserTimes", "-1") ' 剩余使用天数
            gVisionFailedPath = GetSetting("XCPro", "Settings", "VisionFailedPath", "C:\VisionFailed\") ' 视觉失败图像保存路径
            TextBox4.Text = gVisionFailedPath
            If gUserTime <= -1 Then
                SaveSetting("XCPro", "Settings", "UserTimes", "90")
            End If

            OPC_Machine_AddScrew.AddScrewCount_Feeder1 = GetSetting("XCPro", "Settings", "ScrewCountFeeder1", 0)
            OPC_Machine_AddScrew.AddScrewCount_Feeder2 = GetSetting("XCPro", "Settings", "ScrewCountFeeder2", 0)

            If gCurrProName <> "" Then
                TCmbPro.Items.Add(gCurrProName)
                TCmbPro.SelectedItem = gCurrProName
            End If

            gCheckIndex = 1
        Catch ex As Exception
            MsgBox("initParam:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
    End Sub

    Public Sub InitCom() '初始化通讯相关
        Try
            sphelper = New Common.SerialPortHelper("COM1", 9600, IO.Ports.Parity.None, 8, IO.Ports.StopBits.One)
            sphelper.InitSerialPort(SP1)
        Catch ex As Exception
            MsgBox("初始化COM1失败!" & ex.Message.ToString & ex.StackTrace.ToString)
            'Error_report_storage(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), ex.Message.ToString, "待分析", "咨询生产厂商", "软件故障")   '''信息写入数据库中
        End Try
    End Sub

    Private Sub SP1_DataReceived(sender As Object, e As IO.Ports.SerialDataReceivedEventArgs) Handles SP1.DataReceived
        Dim s As String = sphelper.SP_DataReceived(sender)
        SerialPortRecive = s
    End Sub

    'Private Sub Open_Click_PLC()    '角度初始化

    '    Dim iReturnCode As Integer              'Return code
    '    Dim iLogicalStationNumber As Integer = 1    'LogicalStationNumber for ActUtlType
    '    Try
    '        AxActUtlType1.ActLogicalStationNumber = iLogicalStationNumber

    '        iReturnCode = AxActUtlType1.Open()

    '        If iReturnCode = 0 Then
    '            'AppendInfoToTextBox("Open_Click_PLC_OK")
    '            ReciveFlag = "Open_Click_PLC_OK"
    '            Button_PLC.Text = "连接"
    '            Button_PLC.BackColor = Color.GreenYellow
    '        Else
    '            'AppendInfoToTextBox("Open_Click_PLC_Failed")
    '            ReciveFlag = "Open_Click_PLC_Failed"
    '            Button_PLC.Text = "未连接"
    '            Button_PLC.BackColor = Color.YellowGreen
    '        End If
    '        'log.WriteInfoTo_ResultLog_RichTextBox(RichTextBox_log, ReciveFlag + vbCrLf)
    '        AppendInfoToTextBox(ReciveFlag + vbCrLf)
    '    Catch ex As Exception
    '        MsgBox("Open_Click_PLC:" & ex.Message.ToString & ex.StackTrace.ToString)
    '        Error_report_storage(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), ex.Message.ToString, "待分析", "咨询生产厂商", "软件故障")   '''信息写入数据库中
    '    End Try
    'End Sub
    Public Sub InitSetting()

        Try
            Debugpath = My.Application.Info.DirectoryPath

            Dim OpenPsetsetting As Boolean = Exists(gProDataPath & TCmbPro.Text & "\Psetsetting.txt")
            Dim openhistroy As Boolean = Exists(CD_Dir & "上位机资料" & "\log" & "\" & "System_Histroy_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt")
            Dim openSet As Boolean = Exists(gProDataPath & "\Set.txt")
            Dim openGet As Boolean = Exists(gProDataPath & "\Get.txt")
            Dim Alarmsetting As Boolean = Exists(gProDataPath & "Alarmsetting.txt")
            Dim Access As Boolean = Exists(gProDataPath & "\Robot_Or_Access.txt")
            Dim openParameter As Boolean = Exists(gProDataPath & TCmbPro.Text & "\Parameter.txt")

            Dim PonLineIP As Boolean = Exists(gProDataPath & "\PonLineIP.txt")

            Dim PsetCompensate As PsetSetting
            Dim newset1 As Boolean
            Dim Alarmsettinginfo As AlarmSetting = New AlarmSetting
            Dim i As Integer

            If openhistroy = False Then
                SaveSetting("XCPro", "Settings", "UserTimes", gUserTime - 1)
                Dim fileNum As Integer
                fileNum = FreeFile()
                FileOpen(fileNum, CD_Dir & "上位机资料" & "\log" & "\" & "System_Histroy_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt", OpenMode.Append)
                FileClose(fileNum)
            End If
            FileClose(file_num_count)
            If Directory.Exists(gProDataPath & "\") = False Then  '判断文件夹是否存在
                Directory.CreateDirectory(gProDataPath & "\")
            End If
            Try
                FileOpen(file_num_count, gProDataPath & "\count.txt", OpenMode.Random, , , RecordLength:=Len(Todaycount))
                Do While Not EOF(file_num_count)
                    FileGet(file_num_count, Todaycount)
                Loop
            Catch ex As Exception
                AppendInfoToTextBox("读取生产数据错误，错误信息:" + ex.Message)
            Finally
                FileClose(file_num_count)
            End Try

            TextBox1.Text = Todaycount.ScanSN.ToString
            ScrewCount.Text = Todaycount.ScrewCount.ToString
            PassCount.Text = Todaycount.PassCount.ToString
            NGCount.Text = Todaycount.NGCount.ToString
            SCount.Text = Todaycount.SCount.ToString
            ScrewFailed1.Text = Todaycount.ScrewFailed1
            ScrewFailed2.Text = Todaycount.ScrewFailed2
            ScrewFailed3.Text = Todaycount.ScrewFailed3
            ScrewFailed4.Text = Todaycount.ScrewFailed4
            ScrewFailed5.Text = Todaycount.ScrewFailed5
            ScrewFailed6.Text = Todaycount.ScrewFailed6
            ScrewFailed7.Text = Todaycount.ScrewFailed7
            ScrewFailed8.Text = Todaycount.ScrewFailed8
            ScrewFailed9.Text = Todaycount.ScrewFailed9
            ScrewFailed10.Text = Todaycount.ScrewFailed10
            ScrewFailed11.Text = Todaycount.ScrewFailed11
            ScrewFailed12.Text = Todaycount.ScrewFailed12
            ScrewFailed13.Text = Todaycount.ScrewFailed13
            ScrewFailed14.Text = Todaycount.ScrewFailed14
            ScrewFailed15.Text = Todaycount.ScrewFailed15
            ScrewFailed16.Text = Todaycount.ScrewFailed16
            ScrewFailed17.Text = Todaycount.ScrewFailed17
            ScrewFailed18.Text = Todaycount.ScrewFailed18
            ScrewFailed19.Text = Todaycount.ScrewFailed19
            ScrewFailed20.Text = Todaycount.ScrewFailed20
            ScrewFailed21.Text = Todaycount.ScrewFailed21
            ScrewFailed22.Text = Todaycount.ScrewFailed22
            ScrewFailed23.Text = Todaycount.ScrewFailed23
            ScrewFailed24.Text = Todaycount.ScrewFailed24
            ScrewFailed25.Text = Todaycount.ScrewFailed25
            ScrewFailed26.Text = Todaycount.ScrewFailed26
            ScrewFailed27.Text = Todaycount.ScrewFailed27
            ScrewFailed28.Text = Todaycount.ScrewFailed28
            ScrewFailed29.Text = Todaycount.ScrewFailed29
            ScrewFailed30.Text = Todaycount.ScrewFailed30
            TxtBlowNum.Text = Todaycount.ScrewFailed35
            bzw = 0
            If PassCount.Text = "0" Or ScrewCount.Text = "0" Then
                TextBox7.Text = "100.00 %"
            Else
                Dim ng As Double = 100 * (1 - Val(SCount.Text) / Val(ScrewCount.Text))
                TextBox7.Text = Format(ng, "0.00") & " %"
            End If
            TextBox_PCSFailed.Text = Todaycount.PCSFailedCount
            SuctionCount.Text = Todaycount.SuctionCount
            TextBox_CT.Text = Todaycount.CycleTime
            If PassCount.Text = "0" Then
                TextBox_Yield.Text = "100.00 %"
            Else
                Dim ng As Double = 100 * (1 - Val(TextBox_PCSFailed.Text) / Val(PassCount.Text))
                TextBox_Yield.Text = Format(ng, "0.00") & " %"
            End If

            'SN异常
            FileOpen(file_num_count1, gProDataPath & "\count1.txt", OpenMode.Random, , , RecordLength:=Len(Todaycount))
            Do While Not EOF(file_num_count)
                FileGet(file_num_count1, Todaycount1)
            Loop
            FileClose(file_num_count1)
            'SNCount.Text = Todaycount1.SNCount.ToString
            'SN_Check.Text = Todaycount1.SN_Check.ToString

            Dim Robot_Or_Access As Integer = FreeFile()
            If Access = True Then
                FileOpen(Robot_Or_Access, gProDataPath & "\" & "Robot_Or_Access.txt", OpenMode.Random)
                FileGet(Robot_Or_Access, Upload_enable)
                FileClose(Robot_Or_Access)
            Else
                Upload_enable = False
            End If

            '加载螺丝参数
            If openParameter = True Then
                Dim file_num As Integer = FreeFile()
                FileOpen(file_num, gProDataPath & "\" & TCmbPro.Text & "\Parameter.txt", OpenMode.Random)
                FileGet(file_num, CurScrewPara)
                TextBox_CurScrewSN.Text = CurScrewPara.ScrewSN
                FileClose(file_num)
            Else
                AppendInfoToTextBox("未设置螺丝颗数")
            End If
            '加载设置参数
            If OpenPsetsetting = True Then
                Dim file_num As Integer = FreeFile()
                FileOpen(file_num, gProDataPath & "\" & TCmbPro.Text & "\Psetsetting.txt", OpenMode.Random)
                Dim j As Integer = 0

                Do While Not EOF(file_num)
                    FileGet(file_num, PsetCompensate)
                    Pset(j) = PsetCompensate

                    j += 1
                Loop
                NumberOfPSetArray = j
                FileClose(file_num)
            Else
                For i = 0 To NumberOfPSetArray - 1
                    Pset(i).XPosCompensate = 0
                    Pset(i).YPosCompensate = 0
                    Pset(i).ZPosCompensate = 0
                Next
            End If

            If Alarmsetting = True Then
                Dim file_num As Integer = FreeFile()
                FileOpen(file_num, gProDataPath & "\alarmsetting.txt", OpenMode.Random, OpenAccess.Default, OpenShare.Default, 1000)
                Dim j As Integer = 0
                Do While Not EOF(file_num)
                    FileGet(file_num, Alarmsettinginfo)
                    myalarm(j) = Alarmsettinginfo
                    j += 1
                Loop
                NumberOfAlarmArray = j
                FileClose(file_num)
            Else
                For i = 0 To NumberOfAlarmArray - 1
                    myalarm(i).AlarmID = 0
                    myalarm(i).AlarmInfo = ""
                    myalarm(i).Alarmprocess = ""
                Next

            End If

            If openSet = True Then
                Dim file_num As Integer = FreeFile()
                FileOpen(file_num, gProDataPath & "\Set.txt", OpenMode.Random)
                Dim j As Integer = 0
                Do While Not EOF(file_num)
                    FileGet(file_num, newset1)
                    newset(j) = newset1
                    j += 1
                Loop
                NumberOfSet = j
                FileClose(file_num)
            Else
                For i = 0 To NumberOfSet - 1
                    newset(i) = False
                Next
            End If

            If openGet = True Then
                Dim file_num As Integer = FreeFile()
                FileOpen(file_num, gProDataPath & "\Get.txt", OpenMode.Random)
                Dim j As Integer = 0
                Do While Not EOF(file_num)
                    FileGet(file_num, PsetCompensate)
                    Pget(j) = PsetCompensate
                    j += 1
                Loop
                ADD_Screw_Count = Pget(3).XPosCompensate
                Retry_Times = Pget(3).YPosCompensate
                Clear_Time = Pget(3).ZPosCompensate
                NumberOfGet = j
                FileClose(file_num)
            Else
                For i = 0 To NumberOfGet - 1
                    Pget(i).XPosCompensate = 0
                    Pget(i).YPosCompensate = 0
                    Pget(i).ZPosCompensate = 0
                Next
                Pget(2).XPosCompensate = -1
                Pget(2).YPosCompensate = 1
                Pget(2).ZPosCompensate = 0.5
                Pget(3).XPosCompensate = 120
                Pget(3).YPosCompensate = 2
                Pget(3).ZPosCompensate = 8

                ADD_Screw_Count = Pget(3).XPosCompensate
                Retry_Times = Pget(3).YPosCompensate
                Clear_Time = Pget(3).ZPosCompensate
            End If

            '联机IP
            Dim PonLJ As Integer = FreeFile()

            Dim IPDate As String = ""
            Dim LineIP() As String
            If PonLineIP = True Then
                FileOpen(PonLJ, gProDataPath & "\PonLineIP.txt", OpenMode.Random)
                FileGet(PonLJ, IPDate)
                LineIP = Split(IPDate, ",")
                For i = 0 To UBound(LineIP) - 1
                    LineIP_Date(i) = LineIP(i)
                Next
                FileClose(PonLJ)
            Else
                For i = 0 To 3
                    LineIP_Date(i) = "0"
                Next
            End If
            FileClose(PonLJ)

            '获取打螺丝参数
            GetPointPara()

            '获取斜锁路锁付方式
            GetPointWay()

            OPC_RefreshData_Parameter()

            '保存特殊料漏锁
            Dim KeyPassfile_num As Integer = FreeFile()
            Dim KeyPartPass As Boolean = Exists(gProDataPath & "\" & TCmbPro.Text & "\KeyPartPass.txt")
            If KeyPartPass Then
                FileOpen(KeyPassfile_num, gProDataPath & "\" & TCmbPro.Text & "\KeyPartPass.txt", OpenMode.Random)
                FileGet(KeyPassfile_num, KeyPartPassTXT)
                FileClose(KeyPassfile_num)
            Else
                KeyPartPassTXT = "$$"
            End If
            Try
                Dim ss() As String = KeyPartPassTXT.Split("$")(1).Split(",")
                For i = 0 To unLockNO.Length - 1
                    unLockNO(i) = 0
                    If i < ss.Length Then
                        If ss(i) <> "" Then
                            unLockNO(i) = ss(i)
                        End If
                    End If
                Next
            Catch ex As Exception

            End Try
        Catch ex As Exception
            MsgBox("InitSetting:" & ex.Message.ToString & ex.StackTrace.ToString)
            'Error_report_storage(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), ex.Message.ToString, "待分析", "咨询生产厂商", "软件故障")   '''信息写入数据库中
        End Try
    End Sub

    Private Sub GetPointPara()
        Dim i As Integer = 0
        Try
            'Dim DBpath As String = gProDataPath & "\" & TCmbPro.Text & "\PointPara.accdb"
            Dim sql As String = "select * from PointPara where Product='" & TCmbPro.Text & "'"
            Dim pointData As DataSet = New DataSet
            pointData = SearchMysql(sql)
            If pointData.Tables(0).Rows.Count < 10 Then '没有文件,直接跳过
                AppendInfoToTextBox("GetPointPara没有文件")
                Return
            End If
            OPC_Machine_AddScrew.LockCount_Feeder1 = 0
            OPC_Machine_AddScrew.LockCount_Feeder2 = 0
            For i = 1 To 30
                PointPara(i).torque = pointData.Tables(0).Rows(i - 1)(2)
                PointPara(i).angle = pointData.Tables(0).Rows(i - 1)(3)
                PointPara(i).feeder = pointData.Tables(0).Rows(i - 1)(4)
                PointPara(i).diable = pointData.Tables(0).Rows(i - 1)(5)
                Try
                    If PointPara(i).diable = False Then
                        Select Case PointPara(i).feeder
                            Case 1
                                OPC_Machine_AddScrew.LockCount_Feeder1 += 1
                            Case 2
                                OPC_Machine_AddScrew.LockCount_Feeder2 += 1
                        End Select
                    End If
                Catch ex As Exception
                    AppendInfoToTextBox("GetPointPara:" & ex.Message & ex.StackTrace)
                End Try
            Next
            OPC_Refresh_AddScrew()
        Catch ex As Exception
            MsgBox("GetPointPara:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
    End Sub

    Private Sub GetPointWay()
        Dim i As Integer = 0
        Try
            Dim sql1 As String = "select * from PointPara where Product='" & TCmbPro.Text & "'" '产品表单模板名字'产品表单模板名字"
            Dim pointData As DataSet = New DataSet
            pointData = SearchMysql(sql1)
            If pointData.Tables(0).Rows.Count < 10 Then '没有文件,直接跳过
                GoTo d
            End If
            For i = 1 To 30
                PointWay(i) = pointData.Tables(0).Rows(i - 1)(10)
                PointHigh(i) = pointData.Tables(0).Rows(i - 1)(11)
                Point_X轴C(i) = pointData.Tables(0).Rows(i - 1)(12)
                Point_Y轴C(i) = pointData.Tables(0).Rows(i - 1)(13)
            Next
d:
        Catch ex As Exception
            MsgBox("SavePointPara err:" & ex.Message.ToString)
        End Try
    End Sub

    ''' <summary>
    ''' 发送点位斜锁方式,高度,X轴角度,Y轴角度 参数
    ''' </summary>
    ''' <param name="MySocket"></param>
    ''' <param name="StrReceData"></param>
    ''' <remarks></remarks>
    Private Sub SendXieShuJu(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim Strdata As String = ""
        Dim byteSend As Byte()
        Dim i, j As Integer
        j = Val(CurScrewPara.PointCount)
        Try
            For i = 1 To j
                Strdata = Format(PointWay(i), "0.00") + "," + Format(PointHigh(i), "0.00") + "," + Format(Point_X轴C(i), "0.00") + "," + Format(Point_Y轴C(i), "0.00") + ","
                byteSend = Encoding.ASCII.GetBytes(Strdata + vbCrLf)
                AppendInfoToTextBox("send3:" + Strdata)
                MySocket.Send(byteSend)
                waitstandby(200)
            Next
        Catch ex As Exception
            AppendInfoToTextBox("Err in SendXieShuJu:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
    End Sub

    Public Sub InitTcpSever() '初始化TCP服务器
        Try
            socket.InitTcpSever(mServer, IP, Port)
            Dim receive As SocketReceiveData = New SocketReceiveData(AddressOf RecevDataProcess)
            socket.InitSocketReceiveData(receive)
            'IOT程序服务
            socketIOT.InitTcpSever(mServerIOT, "192.168.1.101", 6666)
            socketIOT.InitSocketReceiveData(receive)
        Catch ex As Exception
            ' MsgBox("InitTcpSever:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
    End Sub

    Public Sub InitBarcodeTcpSever() '初始化扫码TCP服务器
        Try
            socket3.InitTcpSever(mServerBarcode, "192.168.1.101", 9000)
            Dim receive As SocketReceiveData = New SocketReceiveData(AddressOf RecevDataProcess)
            socket3.InitSocketReceiveData(receive)
        Catch ex As Exception
            MsgBox("InitTcpSever:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
    End Sub

    Private Function CheckScanStartString(scanSn As String) As Boolean
        Try
            ' 获取配置值
            Dim configValue As String = machineInfo.ScanStrartString
            Dim configValueLength As String = machineInfo.ScanSnLength

            ' 检查配置是否为空
            If String.IsNullOrEmpty(configValue) Then
                AppendInfoToTextBox("扫码枪开始字符未配置")
                Return False
            End If

            ' 解析并清理开始字符串
            Dim startStrings = configValue.Split(","c) _
                .Select(Function(s) s.Trim()) _
                .Where(Function(s) Not String.IsNullOrEmpty(s)) _
                .ToArray()

            Dim snLength = configValueLength.Split(","c) _
                .Select(Function(s) s.Trim()) _
                .Where(Function(s) Not String.IsNullOrEmpty(s)) _
                .ToArray()

            ' 检查是否配置了有效的开始字符
            If startStrings.Length = 0 Then
                AppendInfoToTextBox("扫码枪开始字符配置无效")
                Return False
            End If

            ' 检查每个开始字符
            For Each startStr As String In startStrings
                If scanSn.StartsWith(startStr, StringComparison.OrdinalIgnoreCase) Then
                    For Each startStrLength As String In snLength
                        If scanSn.Length = startStrLength Then
                            AppendInfoToTextBox($"条码匹配成功: {scanSn} 以 {startStr} 开头")
                        Else
                            AppendInfoToTextBox($"条码匹配成功: {scanSn} 长度不符合设定要求")
                        End If
                    Next

                    Return True
                End If
            Next

            ' 没有匹配项
            AppendInfoToTextBox($"条码不匹配: {scanSn} 未以任何配置的字符开头")
            Return False
        Catch ex As Exception
            AppendInfoToTextBox("检查扫码枪开始字符失败: " & ex.Message)
            Return False
        End Try
    End Function

    Private Sub RecevDataProcess(ByRef MySocket As Socket, ByVal StrReceData As String)
        TextBox_RunStatus.Text = "Run"
        TextBox_RunStatus.BackColor = Color.Lime
        ErrorCode.Text = "NA"
        ErrorCode.BackColor = Color.WhiteSmoke
        StrReceData = New String(StrReceData.TakeWhile(Function(c) AscW(c) <> 0 AndAlso AscW(c) <> 13).ToArray())
        ReciveFlag = StrReceData
        Try
            If MySocket.LocalEndPoint.ToString() = "192.168.1.101:9000" Then
                Try
                    Dim sn As String = StrReceData.Split(",")(1)
                    ScanSNAndMESRequest(sn, "")
                Catch ex As Exception
                End Try
                Return
            End If
            'DIO,INPUT,OUTPUT,时，不打印log
            Dim unlogflag As Boolean = False
            Try
                If StrReceData(0) = "D" Then
                    If StrReceData(1) = "I" Then
                        unlogflag = True
                    End If
                End If
            Catch ex As Exception
                unlogflag = False
            End Try

            If unlogflag = False Then
                AppendInfoToTextBox("接收信息：" + ReciveFlag)
            End If
            Dim resrt As String() = StrReceData.Split(",")

            If resrt(0) = "GET" Then
                '获取条码个数
                If resrt(1) = "SNNUM" Then
                    Dim num As String = ProdInfoQueue.Count
                    Dim byteSend As Byte() = Encoding.ASCII.GetBytes(num & Environment.NewLine)
                    MySocket.Send(byteSend)
                    AppendInfoToTextBox("当前条码个数:" & num)
                    Return
                End If
                '获取当前条码是否是虚拟码
                If resrt(1) = "SV" Then
                    Dim byteSend As Byte() = Encoding.ASCII.GetBytes("OK" & Environment.NewLine)
                    If String.IsNullOrWhiteSpace(SN_TextBox.Text) Or SN_TextBox.Text.Contains("Virtual") Then
                        AppendInfoToTextBox("扫码失败")
                        byteSend = Encoding.ASCII.GetBytes("NG" & Environment.NewLine)
                        MySocket.Send(byteSend)
                        AppendInfoToTextBox("GET,SV,= NG")
                        Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                        Label13.Text = "报警信息：" & "扫码失败" + vbCrLf
                        Panel2.BackColor = Color.Red
                        SaveDeviation1(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, Label13.Text)
                        Return
                    End If
                    MySocket.Send(byteSend)
                    AppendInfoToTextBox("GET,SV,= OK")
                    Return
                End If
            End If
            '
            If resrt(0) = "ERR" Then
                '报警代码1001 吐料时环形传感器未检测到螺丝
                If resrt(1) = "1001" Then
                    OPC_Machine_ProductionLog.Result = "NG"
                    Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                    Label13.Text = "报警信息：" & "吐料时环形传感器未检测到螺丝" + vbCrLf
                    Panel2.BackColor = Color.Red
                    SaveDeviation1(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, Label13.Text)
                    Return
                End If
                '报警代码2001 连续多次多次扫码失败
                If resrt(1) = "2001" Then
                    Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                    Label13.Text = "报警信息：" & "连续多次多次扫码失败" + vbCrLf
                    Panel2.BackColor = Color.Red
                    SaveDeviation1(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, Label13.Text)
                    Return
                End If
            End If

            '拍照点1
            If StrReceData(0) = "1" Then
                OPC_Machine_ProductionLog.Photo_time = DateTime.Now
                onePcsDetailsQueue.Clear() '每颗螺丝序列
                EQ_Status = Equipment_Status._RUN
                IsScrewFail = True    '更新产品异常状态
                If Revedateq = False Then
                    IsScrewFail = False
                    Revedateq = True
                End If
                TextBox_ErrMsg.Text = ""
                Dim SateDate As String = ""
                SateDate = CStr(Pget(6).YPosCompensate) + "," + CStr(Todaycount.PassCount) + "," + CStr(Retry_Times) + ","
                SateDate += CStr(Pget(0).XPosCompensate) + "," + CStr(Pget(0).YPosCompensate) + "," + CStr(Pget(0).ZPosCompensate) + ","
                SateDate += CStr(Pget(1).XPosCompensate) + "," + CStr(Pget(1).YPosCompensate) + "," + CStr(Pget(1).ZPosCompensate) + "," + vbCrLf
                FirstCameraImageProcess(MySocket, StrReceData)
                Dim byteSend As Byte() = Encoding.ASCII.GetBytes(SateDate)   '拍照点偏移、$拍照点合格计数、$从新拍照次数
                MySocket.Send(byteSend)
                AppendInfoToTextBox(SateDate)
                If ProdInfoQueue.Count > 0 Then
                    SN_TextBox.Text = ProdInfoQueue(0).sn
                End If
                Return
            End If
            '拍照点2
            If StrReceData(0) = "2" Then
                SecondCameraImageProcess(MySocket, StrReceData)
                OPC_Machine_ProductionLog.Processing_time = DateTime.Now
                Return
            End If
            'CCD扫描
            If StrReceData(0) = "3" Then         'CCD扫描
                CCDcameraimagescancode(MySocket, StrReceData)
                Dim ScanOK As Boolean = False
                If ProdInfoQueue.Count = 0 Then
                    If newset(7) Then '没开启必须扫码
                        ProdInfoQueue.Clear()
                        Dim p As New ProdInfo
                        p.model_name = Chanpin
                        p.keyParts_rfid = ""
                        p.serial_number = "Virtual_" & Format(DateTime.Now, "MMddHHmmss")
                        p.sn = "Virtual_" & Format(DateTime.Now, "MMddHHmmss")
                        p.status = True
                        p.unlock_flag = False
                        ProdInfoQueue.Enqueue(p)
                        Todaycount.ScanSN += 1
                        TextBox1.Text = Todaycount.ScanSN.ToString
                        AppendInfoToTextBox("添加虚拟SN:" & p.sn)
                        showSNQueueFlag = True
                        ScanOK = False
                    End If
                End If
                If ProdInfoQueue.Count > 0 Then
                    SN_NULLflag = True '记录是否为扫码失败流入的产品
                    SN_TextBox.Text = ProdInfoQueue(0).sn
                    OPC_Machine_ProductionLog.SN = ProdInfoQueue(0).sn
                    OPC_Machine_ProductionLog.IN_time = DateTime.Now
                    OPC_Machine_ProductionLog.Result = "OK"
                    If ProdInfoQueue(0).model_name <> "" And ProdInfoQueue(0).model_name <> "NULL" And newset(8) = True Then
                        If Chanpin <> ProdInfoQueue(0).model_name Then
                            AppendInfoToTextBox(Chanpin & "自动切换为:" & ProdInfoQueue(0).model_name & "(" & ProdInfoQueue(0).sn & ")")
                            initPro(ProdInfoQueue(0).model_name)
                            InitSetting()
                            AppendInfoToTextBox(ProdInfoQueue(0).model_name & "切换机型完成。")
                            ScanOK = True
                        End If
                    End If
                Else '队列中没有数据时
                    AppendInfoToTextBox("相机未扫入SN.")
                    ScanOK = False
                End If
                If ScanOK = False Then
                    AppendInfoToTextBox("相机未扫到条码,采用虚拟条码" + OPC_Machine_ProductionLog.SN)
                    Dim sendStr As String = Chanpin & "," & ScanOK & "," & "False" & "," & unLockNO(0) & "," & unLockNO(1) & "," & unLockNO(2) & "," & unLockNO(3)
                    Dim sendByte() As Byte = Encoding.ASCII.GetBytes(sendStr & vbCrLf)
                    MySocket.Send(sendByte)
                    Can_Barcode = True '可以读码
                Else
                    AppendInfoToTextBox("条码:" + OPC_Machine_ProductionLog.SN)
                    Dim sendStr As String = Chanpin & "," & ScanOK & "," & "False" & "," & unLockNO(0) & "," & unLockNO(1) & "," & unLockNO(2) & "," & unLockNO(3)
                    Dim sendByte() As Byte = Encoding.ASCII.GetBytes(sendStr & vbCrLf)
                    MySocket.Send(sendByte)
                    Can_Barcode = True '可以读码
                End If
                Return
            End If

            If StrReceData(0) = "5" Then
                AppendInfoToTextBox("auto1")
                RunQSocket = MySocket
                RunQFlag = "5"
                Return
            End If

            If StrReceData(0) = "6" Then
                AppendInfoToTextBox("auto2")
                RunQSocket = MySocket
                RunQFlag = "6"
                Return
            End If

            If StrReceData(0) = "7" Then
                AppendInfoToTextBox("auto3")
                RunQSocket = MySocket
                RunQFlag = "7"
                Return
            End If

            If StrReceData(0) = "8" Then
                SendPointPara(MySocket, StrReceData)
                Return
            End If
            'MES过站
            If StrReceData(0) = "9" Then
                Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
                MySocket.Send(sendByte)
                SNInfo.Screw_Qty = CurScrewPara.PointCount
                Return
            End If
            'BLOW,1/2,
            If StrReceData(0) = "B" Then
                If StrReceData(1) = "L" Then 'BLOW,1/2,
                    Try
                        Dim SS() As String = StrReceData.Split(",")
                        If Val(SS(1)) = 1 Then
                            OPC_Machine_AddScrew.BlowScrew_Feeder1 = 1
                            AppendInfoToTextBox("Feeder1吐料上报至IOT。")
                        ElseIf Val(SS(1)) = 2 Then
                            OPC_Machine_AddScrew.BlowScrew_Feeder2 = 1
                            AppendInfoToTextBox("Feeder2吐料上报至IOT。")
                        End If
                        If newset(7) Then 'IOT上传开启
                            OPC_Refresh_AddScrew()
                        End If
                        OPC_Machine_AddScrew.BlowScrew_Feeder1 = 0
                        OPC_Machine_AddScrew.BlowScrew_Feeder2 = 0
                        Todaycount.ScrewFailed35 += 1
                        TxtBlowNum.Text = Todaycount.ScrewFailed35
                    Catch ex As Exception
                    End Try
                    Return
                End If
                If StrReceData(1) = "R" Then 'BREMIND
                    AppendInfoToTextBox("IOT提示缺料情况：" & OPC_AddScrewRemind)
                    Dim byteSend As Byte() = Encoding.ASCII.GetBytes(OPC_AddScrewRemind & vbCrLf)   '拍照点偏移、$拍照点合格计数、$从新拍照次数
                    MySocket.Send(byteSend)
                    'OPC_AddScrewRemind = False
                End If
            End If

            'DIO,INPUT,OUTPUT,
            If StrReceData(0) = "D" Then
                If StrReceData(1) = "I" Then
                    Dim SS() As String = StrReceData.Split(",")
                    If SS.Length >= 3 Then
                        OPC_RefreshData_Sensor(SS(1), SS(2))
                    End If
                    Return
                End If
                If StrReceData(1) = "B" Then
                    SendXieShuJu(MySocket, StrReceData)
                    Return
                End If
            End If
            'M 锁附过程
            If StrReceData(0) = "M" Then
                If StrReceData(1) = "A" Then             '单颗锁附开始
                    Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
                    MySocket.Send(sendByte)
                    OPC_Machine_AddScrew.LackScrew_Feeder1 = 0
                    OPC_Machine_AddScrew.LackScrew_Feeder2 = 0
                    OPC_Refresh_AddScrew()
                    curPcsDetails = New OPC_OnePcsDetails
                    curPcsDetails.StartTime = DateTime.Now

                    Return
                ElseIf StrReceData(1) = "U" Then '真空异常漏锁
                    Flag = "S"
                    Suction = "u"
                    AppendInfoToTextBox("螺丝机吸着真空失败")
                    IsScrewFail = False
                    curPcsDetails.Status = 1
                    curPcsDetails.ErrType = "SCR-C02002" '漏锁
                    curPcsDetails.EndTime = DateTime.Now
                    curPcsDetails.StartTime = curPcsDetails.EndTime
                    curPcsDetails.TorqueValue = 0
                    curPcsDetails.UsedTime = 0
                    curPcsDetails.NumOfScrew = ScrewDnum
                    Erro_Msg += RobotStation & "LS,"
                    Mes_msg += RobotStation & "LS,"
                    AppendInfoToTextBox("第" & ScrewDnum & "颗漏锁！")
                    Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                    Label13.Text = "报警信息：" & "第" & ScrewDnum & "颗漏锁！" + vbCrLf
                    Panel2.BackColor = Color.Red
                    OPC_Refresh_Alarm(5)
                    OPC_Machine_ProductionLog.Result = "NG"
                    '将锁附结果加入队列
                    onePcsDetailsQueue.Enqueue(curPcsDetails)
                    SaveDeviation1(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, Label13.Text)
                    Return
                ElseIf StrReceData(1) = "R" Then '锁附正常/异常 MR,NO,OK/NG,timer/ngcode,datetime,
                    Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
                    MySocket.Send(sendByte)

                    curPcsDetails.EndTime = DateTime.Now
                    Dim NL_Date() As Integer = ReadDeviceRandom_Date32("D126", "1") '获取实时扭力

                    Dim recdata() As String = StrReceData.Split(",")
                    Dim n As Integer = Val(recdata(1))

                    Screw = n
                    Luckttime(n) = Format((curPcsDetails.EndTime.Ticks - curPcsDetails.StartTime.Ticks) / 10000000, "0.00")

                    Todaycount.ScrewCount += 1
                    ScrewCount.Text = Todaycount.ScrewCount.ToString

                    If recdata(2) = "OK" Then '锁附OK
                        curPcsDetails.Status = "OK"
                        If Val(recdata(3)) > 1 Then
                            curPcsDetails.ErrType = "SCR-C02001" '二次取料锁附
                        Else
                            curPcsDetails.ErrType = ""
                        End If
                    ElseIf recdata(2) = "NG" Then '锁滑牙
                        curPcsDetails.Status = "NG"
                        OPC_Refresh_Alarm(6)
                        OPC_Machine_ProductionLog.Result = "NG"
                        curPcsDetails.ErrType = recdata(3) '“SCR-C02003”'锁附失败
                        Flag = "S"
                        Suction = ""
                        AppendInfoToTextBox("第" & Screw & "颗锁附失败！")
                        Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                        Label13.Text = "报警信息：" & "第" & Screw & "颗锁附失败！" + vbCrLf
                        Panel2.BackColor = Color.Red
                        Erro_Msg += RobotStation & "SF,"
                        Mes_msg += RobotStation & "SF,"
                        SaveDeviation1(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, Label13.Text)
                    End If
                    Lucktorque(n) = Val(NL_Date(0)) / 1000
                    LuckState(n) = curPcsDetails.Status
                    Torsion = Lucktorque(n)
                    Torsion = Torsion / 1000
                    MaintainInfo.Screwdriver_Status = 0
                    Try
                        curPcsDetails.TorqueValue = Lucktorque(n)
                        curPcsDetails.UsedTime = Luckttime(n)
                        curPcsDetails.NumOfScrew = n
                    Catch ex As Exception
                    End Try
                    SoveProdCP = True '保存锁附结果
                    onePcsDetailsQueue.Enqueue(curPcsDetails)
                    Return
                End If
            End If
            If StrReceData(0) = "U" Then
                GanhanAngle = GetAngle * 10
                Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
                MySocket.Send(sendByte)
                AppendInfoToTextBox("吸料旋转角度：" & GanhanAngle / 10)
                Return
            End If
            If StrReceData(0) = "R" Then
                Dim recdata() As String = StrReceData.Split(",")
                Angle2 = recdata(1)
                AppendInfoToTextBox(vbCrLf + "角度:" & Angle2 & "C°")
                Dim Angle_n(0) As Integer
                Angle_n(0) = Angle2 * 10
                WriteDeviceRandom_Date32("D254", Angle_n)
                Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
                MySocket.Send(sendByte)
                Return
            End If

            If StrReceData(0) = "X" Then
                photoToRobot(MySocket, StrReceData)
                Return
            End If

            '写入自动匹配的拍照点
            If StrReceData(0) = "K" Then
                kill_InfoProcess(StrReceData)
                Return
            End If
            If StrReceData(0) = "Q" Then
                Dim s() As String = StrReceData.Split(",")
                If s(1) = "1" Then
                    ProdInfoQueue.Clear()
                    'ShowCurrentSNListQueue()
                    showSNQueueFlag = True
                    'If newset(8) = True Then
                    '    Can_Barcode = True
                    'Else
                    '    Can_Barcode = False
                    'End If
                    Dim byteSend As Byte() = Encoding.ASCII.GetBytes(CStr(AddProdflag) + vbCrLf)
                    If AddProdflag = True Then
                        AppendInfoToTextBox("进入制作产品模板程序")
                    Else
                        AppendInfoToTextBox("进入生产产品程序")
                    End If
                    MySocket.Send(byteSend)
                ElseIf s(1) = "2" Then
                    StepOK1 = True
                    StepOK2 = False
                    StepOK3 = False
                ElseIf s(1) = "3" Then
                    StepOK1 = False
                    StepOK2 = False
                    StepOK3 = True
                End If
                Return
            End If

            If StrReceData(0) = "P" Then
                P_InfoProcess(StrReceData)
                Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
                MySocket.Send(sendByte)
                Return
            End If

            If StrReceData(0) = "N" Then
                Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
                MySocket.Send(sendByte)
                Dim recdata() As String = StrReceData.Split(",")
                Dim i As Integer
                Dim Sedate(0) As Integer
                Dim Datesh As String
                i = recdata(1)
                ScrewDnum = i
                Torsion2 = PointPara(i).torque * 100
                Datesh = vbCrLf + "扭力:" & PointPara(i).torque & "kgf*cm" + vbCrLf + "供料器:" + Format(PointPara(i).feeder, 0.0) + vbCrLf
                AppendInfoToTextBox(PointPara(i).torque & "," & Format(PointPara(i).feeder, 0.0))
                '向PLC输入 扭力 刀柄旋转角度
                Sedate(0) = Torsion2
                If torqueTemp <> Sedate(0) Then
                    torqueTemp = Sedate(0) '记录上次发送的扭力值
                    WriteDeviceRandom_Date32("D933", Sedate)
                End If
                Return
            End If

            'CYCLETIME=12S
            If StrReceData(0) = "C" Then
                Try
                    Dim recdata2() As String = StrReceData.Split("=")
                    TextBox_CT.Text = Format(Val(recdata2(1).Split("S")(0)), "0.00") & "s"
                    Todaycount.PassCount += 1
                    PassCount.Text = Todaycount.PassCount.ToString
                    If IsScrewFail = True Then
                        Prod_Stade = "OK"
                    Else
                        Prod_Stade = "NG"
                    End If
                    SNInfo.Status = Prod_Stade
                    SoveProdLuck = True
                    Flag_YUYING = "OK"

                    Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
                    MySocket.Send(sendByte)
                Catch ex As Exception
                    AppendInfoToTextBox("CYCLETIME处理异常：" & ex.Message & ex.StackTrace)
                End Try

                'IOT数据上传
                Try
                    OPC_Machine_ProductionLog.OUT_time = DateTime.Now
                    OPC_Machine_ProductionLog.Refresh_Status = 1
                    processingDetails = New OPC_ProcessingDetails() '锁附详情
                    Dim cnt As Integer = onePcsDetailsQueue.Count
                    If cnt > 0 Then
                        processingDetails = New OPC_ProcessingDetails(cnt)
                        For i As Integer = 0 To cnt - 1
                            processingDetails.objs(i) = onePcsDetailsQueue.Dequeue
                            processingDetails.objs(i).SpecTime = "2.00" '超时最大时间
                        Next
                    End If
                    processingDetails.SN = OPC_Machine_ProductionLog.SN
                    OPC_Machine_ProductionLog.Details = gjson.ToJson(processingDetails)
                    '上传生产数据
                    If newset(7) Then 'IOT上传开启
                        OPC_Refresh_ProductionLog()
                        wait(5)
                        OPC_Refresh_AddScrew()
                        'If OPC_Machine_ProductionLog.SN <> "" Then
                        '    AddResultInfo(OPC_Machine_ProductionLog)
                        'End If
                    Else
                        AppendInfoToTextBox("newset(7):" & newset(7))

                    End If
                    If CurScrewPara.Online_Mod = 4 And newset(7) Then '最后一台
                        'Dim searchSQL As String = "select * from resultinfo where SN=" & "'" & OPC_Machine_ProductionLog.SN & "' and Result='OK'" & " order by IP"
                        'Dim ds As DataSet = New DataSet
                        'ds = SearchMysqlRemote(searchSQL)
                        'Dim mes1 As BODY = New BODY
                        'mes1.DATA = OPC_Machine_ProductionLog.SN
                        'mes1.LINE = machineInfo.Line
                        'mes1.MYGROUP = machineInfo.Device_id
                        'mes1.SECTION = machineInfo.SECTION
                        'mes1.W_STATION = machineInfo.SECTION
                        'If ds IsNot Nothing And ds.Tables(0).Rows.Count > 0 Then
                        '    If ds.Tables(0).Rows.Count = Pget(6).ZPosCompensate Then
                        '        mes1.EC = "N/A"
                        '    Else
                        '        mes1.EC = "FAIL"
                        '    End If

                        '    'For i = 0 To ds.Tables(0).Rows.Count - 1
                        '    '    Dim res As String = ds.Tables(0).Rows(i)("Result").ToString()
                        '    'Next
                        'Else
                        '    mes1.EC = "FAIL"
                        'End If

                        ' Dim SendSN As String = "UPLOAD|" & ProdInfoQueue(0).sn & "|" & JsonHelper.ToJson(mes1) & "|"

                        'Dim SendSN As String = "UPLOAD|" & ProdInfoQueue(0).sn & "|"
                        'AppendInfoToTextBox("向后一台发送数据:" & SendSN)
                        'Globalfunc.SendDataNORePly(SendSN, LineIP_Date(2), LineIP_Date(3), "UTF8")

                        'MES_BaseDataRequestUpload(OPC_Machine_ProductionLog.SN, mes1)
                        'searchSQL = "delete * from resultinfo where SN=" & "'" & OPC_Machine_ProductionLog.SN & "' and Result='OK'" & " order by IP"
                    End If
                Catch ex As Exception
                    AppendInfoToTextBox("生产数据IOT上传异常：" & ex.Message & ex.StackTrace)
                End Try
                '生产流程
                'If ProdInfoQueue.Count > 0 Then
                '    AppendInfoToTextBox(ProdInfoQueue(0).sn & "生产结束。")
                '    Try
                '        '发送当前SN至后设备
                '        'Online_Mod=4 为最后一台设备
                '        If Upload_enable And CurScrewPara.Online_Mod <> 4 Then '参数设置中联机发送SN开启&必须扫描开启
                '            'If CurScrewPara.Online_Mod = 2 Or CurScrewPara.Online_Mod = 3 Then
                '            Dim SendSN As String = "Barcode," & ProdInfoQueue(0).sn & ","
                '            Globalfunc.SendDataNORePly(SendSN, LineIP_Date(2), LineIP_Date(3), "UTF8")
                '            AppendInfoToTextBox("向后一台发送SN数据:" & SendSN & vbCrLf)
                '        End If
                '    Catch ex As Exception
                '    End Try
                '    ProdInfoQueue.Dequeue()
                '    '  ShowCurrentSNListQueue()
                '    showSNQueueFlag = True
                'End If
                Return
            End If

            If StrReceData(0) = "E" Then    '机器人报警E,1,code,
                Dim recdata() As String = StrReceData.Split(",")
                If recdata(1) = "1" Then
                    TextBox_RunStatus.Text = "Alarm"
                    TextBox_RunStatus.BackColor = Color.Red
                    ErrorCode.Text = recdata(2)
                    ErrorCode.BackColor = Color.Red
                    Dim data As String = recdata(2) & ","
                    Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                    Label13.Text = "报警信息：" & "机器人报警：报警编码 " & recdata(2) & vbCrLf
                    Panel2.BackColor = Color.Red
                    AppendInfoToTextBox("机器人报警：报警编码" & recdata(1))
                    OPC_Refresh_Alarm(1)
                    ErrorShow.TextBox1.Text = Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                    ErrorShow.TextBox2.Text = "机器人报警：报警编码 " & recdata(2) & vbCrLf
                    ErrorShow.ShowDialog()
                    SaveDeviation1(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, Label13.Text)
                ElseIf recdata(1) = "2" Then
                    TextBox_RunStatus.Text = "Alarm"
                    TextBox_RunStatus.BackColor = Color.Red
                    ErrorCode.Text = recdata(2)
                    ErrorCode.BackColor = Color.Red
                    Dim data As String = recdata(2) & ","
                    Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                    Label13.Text = "报警信息：" & "机器人报警：紧急停止 " & vbCrLf
                    Panel2.BackColor = Color.Red
                    AppendInfoToTextBox("机器人报警：紧急停止" & recdata(1))
                    OPC_Refresh_Alarm(1)
                    SaveDeviation1(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, Label13.Text)
                End If
                Return
            End If

            If StrReceData(0) = "F" Then
                Dim recdata() As String = StrReceData.Split(",")
                If StrReceData(1) = "1" Then
                    Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                    Label13.Text = "报警信息：" & "BOX托盘到位超时,无产品到位" + vbCrLf + "请检查确认,按复位按钮放行" & vbCrLf
                    Panel2.BackColor = Color.Red
                End If
                'Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
                'MySocket.Send(sendByte)
                Return
            End If

            'IOT,AddScrewRemind,Last_count1,Last_count2,
            If StrReceData(0) = "I" Then
                If StrReceData(1) = "O" Then
                    Dim flags() As String = StrReceData.Split(",")
                    Try
                        If flags.Length > 3 Then
                            If flags(1) = 1 Then
                                OPC_AddScrewRemind = True
                                AppendInfoToTextBox("OPC 远程给定加料提醒！")
                            End If
                            OPC_Machine_AddScrew.LastCount_Feeder1 = flags(2)
                            OPC_Machine_AddScrew.LastCount_Feeder2 = flags(3)
                        End If
                    Catch ex As Exception
                        AppendInfoToTextBox("加料提醒异常：" & ex.Message & ex.StackTrace)
                    End Try
                End If
            End If

            If StrReceData(0) = "S" Then
                'SC
                If StrReceData(1) = "C" Then
                    If Chanpin <> TCmbPro.Text Then '产品变更，重新加载
                        initPro(TCmbPro.Text) '
                        InitSetting()
                    End If
                    RobotParameterSet(MySocket, StrReceData)
                    Can_Barcode = True '可以读码
                    Return
                End If
                'ST-chanpin,(ScanOK),1,2,3,4  询问是否有扫码队列
                If StrReceData(1) = "T" Then
                    Dim ScanOK As Boolean = False
                    Dim unlock As Boolean = False
                    SN_NULLflag = False
                    OPC_Machine_ProductionLog = New OPC_Class.ScrewMachine_ProductionLog

                    If ProdInfoQueue.Count = 0 Then
                        AppendInfoToTextBox("当前队列为空，自动生成虚拟SN")
                        ProdInfoQueue.Clear()
                        Dim p As New ProdInfo
                        p.model_name = Chanpin
                        p.keyParts_rfid = ""
                        p.serial_number = "Virtual_" & Format(DateTime.Now, "MMddHHmmss")
                        p.sn = p.serial_number
                        p.status = True
                        p.unlock_flag = False
                        ProdInfoQueue.Enqueue(p)
                        Todaycount.ScanSN += 1
                        TextBox1.Text = Todaycount.ScanSN.ToString
                        AppendInfoToTextBox("添加虚拟SN:" & p.sn)
                        showSNQueueFlag = True
                    End If

                    If ProdInfoQueue.Count > 0 Then
                        SN_NULLflag = True '记录是否为扫码失败流入的产品
                        SN_TextBox.Text = ProdInfoQueue(0).sn
                        OPC_Machine_ProductionLog.SN = ProdInfoQueue(0).sn
                        OPC_Machine_ProductionLog.IN_time = DateTime.Now
                        OPC_Machine_ProductionLog.Result = "OK"
                        If ProdInfoQueue(0).model_name <> "" And ProdInfoQueue(0).model_name <> "NULL" And newset(8) = True Then
                            If Chanpin <> ProdInfoQueue(0).model_name Then
                                AppendInfoToTextBox(Chanpin & "自动切换为:" & ProdInfoQueue(0).model_name & "(" & ProdInfoQueue(0).sn & ")")
                                initPro(ProdInfoQueue(0).model_name)
                                InitSetting()
                                AppendInfoToTextBox(ProdInfoQueue(0).model_name & "切换机型完成。")
                            End If
                        End If
                        '判断是否有rfid银行卡-测试地址http://10.2.72.131:9000/api/gateway
                        Dim reMsg As String = ProdInfoQueue(0).keyParts_rfid 'MES_kittingBomRequest(ProdInfoQueue(0).sn)
                        If reMsg <> "" Then
                            Dim kpSN() As String = KeyPartPassTXT.Split("$")(0).Split(",")
                            For i As Integer = 0 To kpSN.Length - 1
                                If kpSN(i) <> "" Then
                                    If reMsg.Contains(kpSN(i)) Then
                                        unlock = True
                                        AppendInfoToTextBox("物料中包含" & kpSN(i) & ",不锁" & KeyPartPassTXT.Split("$")(1))
                                    End If
                                End If
                            Next
                        End If
                        ScanOK = True
                    Else '队列中没有数据时
                        AppendInfoToTextBox(vbCrLf & "扫码枪未扫入SN.")
                    End If
                    Dim sendStr As String = Chanpin & "," & ScanOK & "," & unlock & "," & unLockNO(0) & "," & unLockNO(1) & "," & unLockNO(2) & "," & unLockNO(3)
                    AppendInfoToTextBox(sendStr)
                    Dim sendByte() As Byte = Encoding.ASCII.GetBytes(sendStr & vbCrLf)
                    MySocket.Send(sendByte)
                    Can_Barcode = True '可以读码
                    Return
                End If
                If StrReceData(1) = "E" Then
                    If ProdInfoQueue.Count > 0 Then
                        AppendInfoToTextBox(ProdInfoQueue(0).sn & "生产结束。")
                        Try
                            '发送当前SN至后设备
                            'Online_Mod=4 为最后一台设备
                            If Upload_enable And CurScrewPara.Online_Mod <> 4 Then '参数设置中联机发送SN开启&必须扫描开启
                                Dim SendSN As String = "Barcode," & ProdInfoQueue(0).sn & "," & ProdInfoQueue(0).model_name & ","
                                Globalfunc.SendDataNORePly(SendSN, LineIP_Date(2), LineIP_Date(3), "UTF8")
                                AppendInfoToTextBox("向后一台发送SN数据:" & SendSN)
                            End If
                        Catch ex As Exception
                            AppendInfoToTextBox(ex.Message)
                        End Try
                        'CurScrewPara.Online_Mod = 1'单独不联机
                        'CurScrewPara.Online_Mod = 2'联机第一台
                        'CurScrewPara.Online_Mod = 3'联机中间
                        'CurScrewPara.Online_Mod = 4'联机最后
                        Try
                            If machineInfo.FirstClearQuene = "1" And CurScrewPara.Online_Mod = 2 Then
                                ClearAllQuene()
                            ElseIf machineInfo.ClearQuene = "1" And (CurScrewPara.Online_Mod = 1 Or CurScrewPara.Online_Mod = 3 Or CurScrewPara.Online_Mod = 4) Then
                                ClearAllQuene()
                            Else
                                ProdInfoQueue.Dequeue()
                                showSNQueueFlag = True
                            End If
                        Catch ex As Exception
                            AppendInfoToTextBox(ex.Message)
                        End Try
                    End If
                    SN_TextBox.Clear()
                    Dim sendByte() As Byte = Encoding.ASCII.GetBytes("OK" & vbCrLf)
                    MySocket.Send(sendByte)
                    Return
                End If
            End If

            '数据上传IOT功能监视
            If StrReceData(0) = "T" Then
                Dim re As String = CheckIOTexe()
                AppendInfoToTextBox(re)
                Dim sendByte() As Byte = Encoding.ASCII.GetBytes(re & vbCrLf)
                MySocket.Send(sendByte)
                Return
            End If

            '报警信息处理
            If StrReceData(0) = "A" Then    '
                Dim recdata() As String = StrReceData.Split(",")
                Dim Recda As String
                Recda = Format(Val(recdata(1)), 0)
                If Recda = "1" Then
                    If Val(recdata(2)) = 0 Then
                        AppendInfoToTextBox("吸螺丝失败")
                        Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                        Label13.Text = "报警信息：" & "吸螺丝失败" + vbCrLf
                        Panel2.BackColor = Color.Red
                        SaveDeviation1(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, Label13.Text)
                    Else
                        AppendInfoToTextBox("第" + Format(Val(recdata(2)), 0) + "颗吸螺丝失败")
                        Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                        Label13.Text = "报警信息：" & "第" + Format(Val(recdata(2)), 0) + "颗吸螺丝失败" + vbCrLf
                        Panel2.BackColor = Color.Red
                        SaveDeviation1(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, Label13.Text)
                    End If
                    OPC_Refresh_Alarm(2)
                ElseIf Recda = "2" Then
                    Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                    Label13.Text = "报警信息：" & "设备气压低,请检查设备进气压" + vbCrLf
                    Panel2.BackColor = Color.Red
                    AppendInfoToTextBox("设备气压低,请检查设备进气压")
                    OPC_Refresh_Alarm(3)
                    SaveDeviation1(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, Label13.Text)
                ElseIf Recda = "3" Then
                    OPC_Machine_ProductionLog.Processing_time = DateTime.Now
                    OPC_Machine_ProductionLog.Result = "NG"
                    IsScrewFail = False
                    OPC_Refresh_Alarm(4)
                    Todaycount.NGCount += 1
                    NGCount.Text = Todaycount.NGCount.ToString
                    curPcsDetails.Status = 1
                    curPcsDetails.ErrType = "SCR-C02005" '拍照失败
                    curPcsDetails.EndTime = DateTime.Now
                    curPcsDetails.StartTime = curPcsDetails.EndTime
                    curPcsDetails.TorqueValue = 0
                    curPcsDetails.UsedTime = 0
                    curPcsDetails.NumOfScrew = 0
                    '将锁附结果加入队列
                    onePcsDetailsQueue.Enqueue(curPcsDetails)
                    'TextBox_ErrMsg.AppendText(DateTime.Now + "拍照识别失败" + vbCrLf)
                    Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                    Label13.Text = "报警信息：" & "拍照识别失败" + vbCrLf
                    Panel2.BackColor = Color.Red
                    AppendInfoToTextBox("拍照点拍照失败")
                    Prod_Stade = "NG"
                    Flag_YUYING = "OK"
                    SaveDeviation1(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, Label13.Text)
                ElseIf Recda = "4" Then
                    Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                    Label13.Text = "报警信息：" & "检测到产品被带起" + vbCrLf + "请确认产品位置" + vbCrLf
                    Panel2.BackColor = Color.Red
                    AppendInfoToTextBox("检测到产品被带起,请确认产品位置")
                    OPC_Refresh_Alarm(3)
                    SaveDeviation1(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, Label13.Text)
                ElseIf Recda = "7" Then
                    OPC_Refresh_Alarm(7)
                    Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                    Label13.Text = "报警信息：" & "供料器缺料,请检查供料器是否卡料" + vbCrLf
                    Panel2.BackColor = Color.Red
                    AppendInfoToTextBox("供料器缺料,请检查供料器是否卡料")
                    SaveDeviation1(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, Label13.Text)
                    Try
                        If recdata(2) = 1 Then 'A,7,1/2, 供料器1/2缺料
                            OPC_Machine_AddScrew.LackScrew_Feeder1 = 1
                        ElseIf recdata(2) = 2 Then
                            OPC_Machine_AddScrew.LackScrew_Feeder2 = 1
                        End If
                        OPC_Refresh_AddScrew()
                    Catch ex As Exception

                    End Try
                End If
                Return
            End If
        Catch ex As Exception
            MsgBox("RecevDataProcess:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
    End Sub

    ''' <summary>
    ''' 插入结果数据到远程数据库
    ''' </summary>
    ''' <param name="oPC_Machine_ProductionLog"></param>
    Private Sub AddResultInfo(oPC_Machine_ProductionLog As OPC_Class.ScrewMachine_ProductionLog)
        Dim sql As String = "insert into resultinfo(SN,Refresh_Status,Result,Details,IP)values(" & "'" & oPC_Machine_ProductionLog.SN & "'" + "," & oPC_Machine_ProductionLog.Refresh_Status & "," & "'" & oPC_Machine_ProductionLog.Result & "'" & "," & "'" & oPC_Machine_ProductionLog.Details & "'" & "," & "'" & LineIP_Date(0) & "'" & ")"
        Dim res As Integer = HandleMysqlRemote(sql)
        AppendInfoToTextBox(sql)
        If res > 0 Then
            AppendInfoToTextBox("结果数据写入成功")
        End If
    End Sub

    Private Function CheckIOTexe() As Boolean
        Try
            If newset(7) Then 'IOT功能未开启时
                Dim uploadFlag, IOTFlag As Boolean
                For Each pro As Process In Process.GetProcesses()
                    If pro.ProcessName = "Upload" Or pro.ProcessName = "数据上传" Or pro.ProcessName = "upload" Then
                        uploadFlag = True
                    End If
                    'If pro.ProcessName = "ITOTAgent_OPCUA" Then
                    IOTFlag = True
                    'End If

                    If uploadFlag And IOTFlag Then
                        Exit For
                    End If
                Next
                If uploadFlag = False Then
                    Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                    Label13.Text = "报警信息：" & "上位机报警：报警编码" & "upload.exe未打开！" & vbCrLf
                    SaveDeviation1(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, Label13.Text)
                End If
                If IOTFlag = False Then
                    Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                    Label13.Text = "报警信息：" & "上位机报警：报警编码" & "IOT未打开！" & vbCrLf
                    SaveDeviation1(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, Label13.Text)
                End If
                If uploadFlag = True And IOTFlag = True Then
                    Return True
                End If
            Else
                Label26.Text = "报警时间：" & Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss")
                Label13.Text = "报警信息：" & "上位机报警：报警编码" & "设备数据上传未勾选！！" & vbCrLf
                SaveDeviation1(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, Label13.Text)
                Return False
            End If
        Catch ex As Exception
        End Try
        Return False
    End Function

    Public Sub InitTcpSever2() '初始化TCP服务器
        Dim mServer2(1) As Socket
        Dim IP2 As String = LineIP_Date(0)
        Dim Port2 As Integer = Val(LineIP_Date(1))
        Try
            socket2.InitTcpSever(mServer2, IP2, Port2)
            Dim receive As SocketReceiveData = New SocketReceiveData(AddressOf RecevDataProcess2)
            socket2.InitSocketReceiveData(receive)
            Button_LJ.Text = "打开"
            Button_LJ.BackColor = Color.GreenYellow
            Bfalge = True
        Catch ex As Exception
            Bfalge = False
            Button_LJ.Text = "关闭"
            Button_LJ.BackColor = Color.YellowGreen
            '  MsgBox("InitTcpSever:" & ex.Message.ToString & ex.StackTrace.ToString)
            'Error_report_storage(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), ex.Message.ToString, "待分析", "咨询生产厂商", "软件故障")   '''信息写入数据库中
        End Try
    End Sub

    Private Sub RecevDataProcess2(ByRef MySocket2 As Socket, ByVal StrReceData2 As String)
        'log.WriteInfoTo_ResultLog_RichTextBox(RichTextBox_log, "接收前一台数据:" + StrReceData2 + vbCrLf)
        StrReceData2 = New String(StrReceData2.TakeWhile(Function(c) AscW(c) <> 0 AndAlso AscW(c) <> 13).ToArray())
        SeverDate = "接收端口：" + MySocket2.LocalEndPoint.ToString() + "，接收数据：" + StrReceData2 + vbCrLf
        AppendInfoToTextBox("接收前一台数据:" + StrReceData2)
        'Dim recdata() As String = StrReceData2.Split(",")
        'If recdata(0) = "NG" Then
        '    Revedateq = False
        'ElseIf recdata(0) = "OK" Then
        '    Revedateq = True
        'Else
        '    TCmbPro.Text = recdata(0)
        'End If
        Try
            'Barcode,12324214214124,
            If StrReceData2(0) = "B" Then
                Try
                    'Dim sn As String = StrReceData2.Split(",")(1)
                    Dim sn() As String = StrReceData2.Split(",")
                    ScanSNAndMESRequest(sn(1), sn(2))
                Catch ex As Exception
                End Try
                Return
            End If
            If StrReceData2.Contains("UPLOAD") Then
                Dim readstr As String() = StrReceData2.Split("|")
                '上传MES 信息
                If readstr(0) = "UPLOAD" Then
                    Try
                        'MES_BaseDataRequestUpload(readstr(1), readstr(2))
                        ' Dim searchSQL As String = "delete * from resultinfo where SN=" & "'" & readstr(1) & "'"
                        Dim searchSQL As String = "DELETE FROM `lcfc`.`resultinfo` WHERE `SN` = '" & readstr(1) & "'"
                        AppendInfoToTextBox(searchSQL)
                        HandleMysqlRemote(searchSQL)
                    Catch ex As Exception
                        AppendInfoToTextBox("数据上传到MES错误，错误信息：" + ex.Message)
                    End Try
                    Return
                End If
            End If
        Catch ex As Exception

        End Try
    End Sub

    Public Sub photoToRobot(ByRef MySocket As Socket, ByVal StrReceData As String)
        Try
            '从数据库中读取拍照点坐标
            'Dim DBpath As AccessHelper = New AccessHelper("Tool\" & Chanpin & "\photo_point.accdb")
            'Dim sql As String = "select * from domino"
            'Dim ds As DataSet = New DataSet
            'ds = DBpath.SearchAccess(sql)

            Dim ds As DataSet = New DataSet
            Dim sql As String = "select * from photo_point where Product='" & Chanpin & "'" '产品表单模板名字'产品表单模板名字"
            ds = New DataSet
            ds = SearchMysql(sql)

            Dim w As Integer
            For w = 0 To 2
                Dim m As Integer = 4 * w
                photo_point(m) = Val(ds.Tables(0).Rows(w)(2))
                photo_point(m + 1) = Val(ds.Tables(0).Rows(w)(3))
                photo_point(m + 2) = Val(ds.Tables(0).Rows(w)(4))
                photo_point(m + 3) = Val(ds.Tables(0).Rows(w)(5))
            Next
            '将拍照点发送至机器人
            Dim strSendData As String = ""
            strSendData = ""
            strSendData = CStr(Format(photo_point(0), "0.000")) + "," + CStr(Format(photo_point(1), "0.000")) + "," + CStr(Format(photo_point(2), "0.000")) + "," + CStr(Format(photo_point(3), "0.000")) + ","
            strSendData += CStr(Format(photo_point(4), "0.000")) + "," + CStr(Format(photo_point(5), "0.000")) + "," + CStr(Format(photo_point(6), "0.000")) + "," + CStr(Format(photo_point(7), "0.000")) + ","
            strSendData += CStr(Format(photo_point(8), "0.000")) + "," + CStr(Format(photo_point(9), "0.000")) + "," + CStr(Format(photo_point(10), "0.000")) + "," + CStr(Format(photo_point(11), "0.000"))

            AppendInfoToTextBox("send:X: " + strSendData)
            Dim i As Integer = 0
            strSendData += vbCrLf
            Dim byteSend As Byte() = Encoding.ASCII.GetBytes(strSendData)
            MySocket.Send(byteSend)
        Catch ex As Exception
            MsgBox("photoToRobot:" & ex.Message.ToString & ex.StackTrace.ToString)
            'Error_report_storage(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), ex.Message.ToString, "待分析", "咨询生产厂商", "软件故障")   '''信息写入数据库中
        End Try

    End Sub

    Private Sub kill_InfoProcess(ByVal str As String)
        Try
            Dim ss() As String = str.Split(",")
            If ss(1) = "1" Then
                ss(1) = "photo1robot"
                AutoAddPhotoPoint(1).X = CStr(ss(2))
                AutoAddPhotoPoint(1).Y = CStr(ss(3))
                AutoAddPhotoPoint(1).Z = CStr(ss(4))
                AutoAddPhotoPoint(1).C = CStr(ss(5))
            ElseIf ss(1) = "2" Then
                ss(1) = "photo2robot"
                AutoAddPhotoPoint(2).X = CStr(ss(2))
                AutoAddPhotoPoint(2).Y = CStr(ss(3))
                AutoAddPhotoPoint(2).Z = CStr(ss(4))
                AutoAddPhotoPoint(2).C = CStr(ss(5))
            ElseIf ss(1) = "3" Then
                ss(1) = "photo3robot"
            End If
            'Dim DBpath As AccessHelper = New AccessHelper("Tool\" & Chanpin & "\photo_point.accdb")
            'Dim sql As String = " update " & " domino " & "set x=" & ss(2) & ",y=" & ss(3) & ",z=" & ss(4) & ",c=" & ss(5) & " where PointName=" & "'" & ss(1) & "'"
            'DBpath.HandleAccess(sql)
            Dim proname As String = "photo_point"
            Dim sql As String = ""
            sql = " update " & proname & " set x=" & ss(2) & ",y=" & ss(3) & ",z=" & ss(4) & ",c=" & ss(5) & " where PointName=" & "'" & ss(1) & "' and Product='" & Chanpin & "'"
            HandleMysql(sql)
        Catch ex As Exception
            'Error_report_storage(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), ex.Message.ToString, "待分析", "咨询生产厂商", "软件故障")   '''信息写入数据库中
            MsgBox("kill_InfoProcess error:" & ex.Message.ToString)
        End Try
    End Sub

    Private Sub LuckDatePoint()
        Try
            Dim sql As String = "select * from domino" '产品表单模板名字'产品表单模板名字"
            Dim DBpath As Common.AccessHelper = New Common.AccessHelper("Tool\" & Chanpin & "\cad_point.accdb")

            Dim ds As DataSet = New DataSet
            ds = DBpath.SearchAccess(sql)
            Dim k As Integer
            '获取cad_point 数据库XY点位
            For k = 4 To 33
                pointCAD_X(k - 4) = Val(ds.Tables(0).Rows(k)(2))
                pointCAD_Y(k - 4) = Val(ds.Tables(0).Rows(k)(3))
                pointCAD_Z(k - 4) = Val(ds.Tables(0).Rows(k)(4))
                pointCAD_C(k - 4) = Val(ds.Tables(0).Rows(k)(5))
            Next
        Catch ex As Exception
            'Error_report_storage(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), ex.Message.ToString, "待分析", "咨询生产厂商", "软件故障")   '''信息写入数据库中
            MsgBox("LuckDatePoint err:" & ex.Message.ToString)
        End Try
    End Sub

    Private Sub P_InfoProcess(ByVal str As String)
        Try
            '
            Dim recdata() As String = str.Split(",")
            temp(0) = photo_point(0)
            temp(1) = photo_point(1)
            'temp(4) = recdata(3)
            temp(2) = photo_point(4)
            temp(3) = photo_point(5)
            bzw = 1
            Dim proname As String = "cad_point"
            Dim Sql As String = "update " & proname & " set x=" & temp(0) & ",y=" & temp(1) & "  where PointName = 'photo1robot ' and Product='" & Chanpin & "'"
            HandleMysql(Sql)
            Sql = "update " & proname & " set x=" & temp(2) & ",y=" & temp(3) & " where PointName = 'photo2robot ' and Product='" & Chanpin & "'"
            HandleMysql(Sql)

            'Dim Sql As String = ""
            'Dim DBpath As AccessHelper = New AccessHelper("Tool\" & Chanpin & "\cad_point.accdb")
            'Dim proname As String = "domino"

            'Sql = "update " & proname & " set x=" & temp(0) & "  where PointName = 'photo1robot '"
            'DBpath.HandleAccess(Sql)

            'Sql = "update " & proname & " set y=" & temp(1) & " where PointName = 'photo1robot '"
            'DBpath.HandleAccess(Sql)

            'Sql = "update " & proname & " set x=" & temp(2) & " where PointName = 'photo2robot '"
            'DBpath.HandleAccess(Sql)

            'Sql = "update " & proname & " set y=" & temp(3) & " where PointName = 'photo2robot '"
            'DBpath.HandleAccess(Sql)

            CadToRobot()    'cad_point计算至Robot_point
        Catch ex As Exception
            'Error_report_storage(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), ex.Message.ToString, "待分析", "咨询生产厂商", "软件故障")   '''信息写入数据库中
            MsgBox("P_InfoProcess err:" & ex.Message.ToString)
        End Try

    End Sub

    ''' <summary>
    ''' 将cad_point 点位计算并储存到robot_point中
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub CadToRobot()

        'Dim sql As String = "select * from domino" '产品表单模板名字'产品表单模板名字"
        'Dim DBpath As AccessHelper = New AccessHelper("Tool\" & Chanpin & "\cad_point.accdb")

        'Dim ds As DataSet = New DataSet
        'ds = DBpath.SearchAccess(sql)
        Dim w As Integer
        Dim proname As String = "cad_point"
        Dim sql As String = "select * from " & proname & " where Product='" & Chanpin & "'" '产品表单模板名字'产品表单模板名字"
        Dim ds As DataSet = New DataSet
        ds = SearchMysql(sql)

        '获取cad_point 数据库XY点位
        For w = 0 To 33
            Dim m As Integer = 2 * w
            pointCAD(m) = Val(ds.Tables(0).Rows(w)(2))
            pointCAD(m + 1) = Val(ds.Tables(0).Rows(w)(3))
        Next
        Dim k As Integer
        '提取1~33点位Z轴数据
        For k = 4 To 33
            pointCAD_Z(k - 4) = Val(ds.Tables(0).Rows(k)(4))
        Next

        '提取1~33点位C轴数据
        For k = 4 To 33
            pointCAD_C(k - 4) = Val(ds.Tables(0).Rows(k)(5))
        Next
        ''提取1~33点位姿态数据
        'For k = 4 To 33
        '    pointCAD_FLG1(k - 4) = Val(ds.Tables(0).Rows(k)(6))
        'Next
        If bzw = 2 Then
            For w = 0 To 3
                pointCAD(w) = temp(w)   ' temp(w)为机器人上传拍照点位
            Next
        End If

        Dim ph1x As Double = pointCAD(0) - pointCAD(4)
        Dim ph1y As Double = pointCAD(1) - pointCAD(5)
        Dim ph2x As Double = pointCAD(2) - pointCAD(6)
        Dim ph2y As Double = pointCAD(3) - pointCAD(7)
        bzw = 1

        TwoPointurn(ph1x, ph1y, ph2x, ph2y)

        Dim s As String = ""
        Dim i
        Dim q

        For i = 0 To 59 '获取计算的偏差结果
            resu(i) = Val(resu(i)) + Val(pointCAD(i + 8))
        Next

        '将点位写入 robot_point 数据库
        'Dim Sql2 As String = ""
        'Dim cnStr2 As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= Tool\" & Chanpin & "\robot_point.accdb;Persist Security Info=False"
        'Dim cn2 As OleDbConnection = New OleDbConnection(cnStr2)
        'Dim dc2 As OleDbCommand
        'cn2.Open() '打开数据库
        'Dim sql2 As String = ""
        'Dim DBpath2 As AccessHelper = New AccessHelper("Tool\" & Chanpin & "\robot_point.accdb")
        Dim Sql2 As String = ""
        proname = "robot_point"

        For k = 0 To 9      '29
            i = 2 * k
            Dim point As String
            q = k + 1
            If q >= 10 Then
                point = "set" & q
            Else
                point = "set0" & q
            End If
            Sql2 = "update " & proname & " set x=" & resu(i) & ",y=" & resu(i + 1) & ",z=" & pointCAD_Z(k) & ",c=" & pointCAD_C(k) & " where pointname = '" & point & " ' and Product='" & Chanpin & "'"
            HandleMysql(Sql2)

            'sql2 = "update " & "domino" & " set x=" & resu(i) & " where pointname = '" & point & " '"
            'DBpath2.HandleAccess(sql2)
            'sql2 = "update " & "domino" & " set y=" & resu(i + 1) & " where pointname = '" & point & " '"
            'DBpath2.HandleAccess(sql2)
            'sql2 = "update " & "domino" & " set z=" & pointCAD_Z(k) & " where pointname = '" & point & " '"
            'DBpath2.HandleAccess(sql2)
            'sql2 = "update " & "domino" & " set c=" & pointCAD_C(k) & " where pointname = '" & point & " '"
            'DBpath2.HandleAccess(sql2)
        Next

    End Sub

    Private Sub SendPointPara(ByRef MySocket As Socket, ByVal StrReceData As String)
        Try
            Dim Strdata As String = ""
            Dim Strdata1 As String = ""
            Dim Pangle(30) As Double
            Dim i, j As Integer

            j = Val(CurScrewPara.PointCount)
            For i = 1 To j
                Strdata = CStr(Format(PointPara(i).torque, "0.00")) + "," + CStr(Format(PointPara(i).feeder, "0.00")) + "," + CStr(PointPara(i).diable) + "," + CStr(Format(PointPara(i).angle, "0.00"))
                Dim byteSend As Byte() = Encoding.ASCII.GetBytes(Strdata + vbCrLf)
                AppendInfoToTextBox("send:" + Strdata)
                MySocket.Send(byteSend)
            Next
        Catch ex As Exception
            MsgBox("SendPointPara:" & ex.Message.ToString & ex.StackTrace.ToString)
            'Error_report_storage(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), ex.Message.ToString, "待分析", "咨询生产厂商", "软件故障")   '''信息写入数据库中
        End Try
    End Sub

#Region "图像处理函数"

    Private Sub FirstCameraImageProcess(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim __time As DateTime = DateTime.Now
        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(0).Tools.Item("相机设定")
            Dim tmpCalibCB As CogCalibCheckerboardTool = gTBCheck(0).Tools.Item("CogCalibCheckerboardTool1")
            'Dim tmpCalibCB As CogCalibNPointToNPointTool = gTBCheck(0).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpCogCalibCheckerboardTool As CogCalibNPointToNPointTool = gTBCheck(0).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpPmalign1 As CogPMAlignTool = gTBCheck(0).Tools.Item("CogPMAlignTool1")

            Dim tmpPmalign As CogPMAlignTool = tmpPmalign1
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim bHasObject As Boolean = False
            Dim score As String = "0.00"
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                If True Then
                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then

                        tmpfifo0.Run()
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        If tmpfifo0.OutputImage IsNot Nothing Then
                            SecondCCDState = 0 '正常
                            tmpCalibCB.Run()
                            tmpCogCalibCheckerboardTool.Run()
                            tmpPmalign1.Run()

                            If tmpPmalign1.RunStatus.Result = CogToolResultConstants.Accept Then
                                If tmpPmalign.Results.Count > 0 Then
                                    SendDataX(0) = tmpPmalign.Results.Item(0).GetPose.TranslationX.ToString
                                    SendDataY(0) = tmpPmalign.Results.Item(0).GetPose.TranslationY.ToString
                                    score = tmpPmalign.Results.Item(0).Score.ToString("0.000")
                                    'SendDataX(1) = tmpPmalign.Results.Item(1).GetPose.TranslationX.ToString
                                    'SendDataY(1) = tmpPmalign.Results.Item(1).GetPose.TranslationY.ToString
                                Else
                                    SendDataX(0) = 999
                                    SendDataY(0) = 999
                                    'SendDataX(1) = 999
                                    'SendDataY(1) = 999
                                End If

                                If tmpPmalign.Results.Count < 1 Then
                                    Dim fileName As String = machineInfo.Device_id & Format(DateAndTime.Now, "yyyyMMddHHmmss") & ".jpg"
                                    Dim filePath As String = gVisionFailedPath & TCmbPro.Text & "\" & Format(Date.Now.Date, "yyyyMMdd") & "\" & Chanpin & "\" & "Fail Image\"
                                    YSPic(CogRecordDisplay1, tmpfifo0, filePath, fileName)
                                End If
c:
                                If SecondCCDState = 2 Then
                                    SendDataX(0) = 999
                                    SendDataY(0) = 999
                                    'SendDataX(1) = 999
                                    'SendDataY(1) = 999
                                End If
                            Else
                                SendDataX(0) = 999
                                SendDataY(0) = 999
                                'SendDataX(1) = 999
                                'SendDataY(1) = 999
                            End If

                            'log.WriteInfoTo_ResultLog_RichTextBox(RichTextBox_log, Format(SendDataX(0), "0.000") & "," & Format(SendDataY(0), "0.000") + vbCrLf)

                            LabVision1.Text = "X:" & SendDataX(0).ToString("0.000") & ",Y:" & SendDataY(0).ToString("0.000") & ",S:" & score
                            AppendInfoToTextBox(SN_TextBox.Text & "-拍照点1-" & LabVision1.Text)

                            If SendDataX(0) < 900 Or SendDataY(0) < 900 Then
                            Else
                                'log.WriteInfoTo_ResultLog_RichTextBox(RichTextBox_log, "第一个拍照点拍照失败", Color.Red)
                                AppendInfoToTextBox("第一个拍照点拍照失败")
                            End If
                            TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"

                            CogRecordDisplay1.Image = tmpfifo0.OutputImage
                            CogRecordDisplay1.Fit()
                            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                CogRecordDisplay1.Record = tmpPmalign.CreateLastRunRecord
                            End If
                        Else
                            SecondCCDState = 3
                        End If

                    End If
                Else
                    SecondCCDState = 1
                End If
            Else
                SecondCCDState = 2
                GoTo c

            End If
        Catch ex As Exception
            MsgBox("FirstCameraImageProcess:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try

d:
    End Sub

    Private Sub SecondCameraImageProcess(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim __time As DateTime = DateTime.Now

        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(1).Tools.Item("相机设定")
            Dim tmpCalibCB As CogCalibCheckerboardTool = gTBCheck(1).Tools.Item("CogCalibCheckerboardTool1")
            'Dim tmpCalibCB As CogCalibNPointToNPointTool = gTBCheck(1).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpCogCalibCheckerboardTool As CogCalibNPointToNPointTool = gTBCheck(1).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpPmalign1 As CogPMAlignTool = gTBCheck(1).Tools.Item("CogPMAlignTool1")

            Dim tmpPmalign As CogPMAlignTool = tmpPmalign1
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim bHasObject As Boolean = False
            Dim score As String = "0.00"
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then

                If True Then
                    'If tmpfifo0.Operator.FrameGrabber.SerialNumber = SecondCCDSerNum Then
                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then

                        tmpfifo0.Run()
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        If tmpfifo0.OutputImage IsNot Nothing Then

                            SecondCCDState = 0 '正常
                            tmpCalibCB.Run()
                            tmpCogCalibCheckerboardTool.Run()
                            tmpPmalign1.Run()
                            Dim dTemp As Double = 0
                            Dim dTemp2 As String = ""

                            If tmpPmalign1.RunStatus.Result = CogToolResultConstants.Accept Then

                                If tmpPmalign.Results.Count > 0 Then
                                    SendDataX(2) = tmpPmalign.Results.Item(0).GetPose.TranslationX.ToString
                                    SendDataY(2) = tmpPmalign.Results.Item(0).GetPose.TranslationY.ToString
                                    score = tmpPmalign.Results.Item(0).Score.ToString("0.000")
                                Else
                                    SendDataX(2) = 9999
                                    SendDataY(2) = 9999
                                End If
                                If tmpPmalign.Results.Count < 1 Then
                                    Dim fileName As String = machineInfo.Device_id & Format(DateAndTime.Now, "yyyyMMddHHmmss") & ".jpg"
                                    Dim filePath As String = gVisionFailedPath & TCmbPro.Text & "\" & Format(Date.Now.Date, "yyyyMMdd") & "\" & Chanpin & "\" & "Fail Image\"
                                    YSPic(CogRecordDisplay2, tmpfifo0, filePath, fileName)
                                End If

c:
                                If SecondCCDState = 2 Then
                                    SendDataX(2) = 9999
                                    SendDataY(2) = 9999
                                End If
                            Else
                                SendDataX(2) = 9999
                                SendDataY(2) = 9999
                            End If

                            LabVision2.Text = "X:" & SendDataX(2).ToString("0.000") & ",Y:" & SendDataY(2).ToString("0.000") & ",S:" & score
                            AppendInfoToTextBox(SN_TextBox.Text & "-拍照点2-" & LabVision2.Text)
                            'Dim cnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= Tool\" & Chanpin & "\robot_point.accdb;Persist Security Info=False"
                            'Dim cn As OleDbConnection
                            'Dim da As OleDbDataAdapter
                            'Dim ds As DataSet

                            'cn = New OleDbConnection(cnStr)
                            'Dim sql As String = "select * from domino" '产品表单模板名字'产品表单模板名字"
                            'da = New OleDbDataAdapter(sql, cn)
                            'ds = New DataSet
                            'da.Fill(ds, "grade")
                            Dim w As Integer
                            Dim sql As String = "select * from robot_point where Product='" & Chanpin & "'" '产品表单模板名字'产品表单模板名字"
                            Dim ds As DataSet = New DataSet
                            ds = SearchMysql(sql)
                            For w = 0 To Val(CurScrewPara.PointCount) - 1
                                Dim k As Integer = 2 * (w + 4)
                                Dim m As Integer = 2 * w
                                pointCAD(k) = Val(ds.Tables(0).Rows(w)(2))
                                pointCAD(k + 1) = Val(ds.Tables(0).Rows(w)(3))
                                pointCAD_Z(w) = Val(ds.Tables(0).Rows(w)(4))
                                pointCAD_Z(w) += Pset(w).ZPosCompensate
                                pointCAD_C(w) = Val(ds.Tables(0).Rows(w)(5))
                                'pointCAD_C(w) += PointPara(w + 1).angle
                            Next
                            pointCAD(4) = photo_point(0)                 '第一个拍照点X
                            pointCAD(5) = photo_point(1)                 '第一个拍照点Y
                            pointCAD(6) = photo_point(4)                 '第二个拍照点X
                            pointCAD(7) = photo_point(5)                 '第二个拍照点Y

                            bzw = 0
                            ReturnXYR = TwoPointurn(SendDataX(0), SendDataY(0), SendDataX(2), SendDataY(2))

                            ReturnXYR.X1 += Pset(0).XPosCompensate + pointCAD(8)
                            ReturnXYR.Y1 += Pset(0).YPosCompensate + pointCAD(9)
                            ReturnXYR.X2 += Pset(1).XPosCompensate + pointCAD(10)
                            ReturnXYR.Y2 += Pset(1).YPosCompensate + pointCAD(11)
                            ReturnXYR.X3 += Pset(2).XPosCompensate + pointCAD(12)
                            ReturnXYR.Y3 += Pset(2).YPosCompensate + pointCAD(13)
                            ReturnXYR.X4 += Pset(3).XPosCompensate + pointCAD(14)
                            ReturnXYR.Y4 += Pset(3).YPosCompensate + pointCAD(15)
                            ReturnXYR.X5 += Pset(4).XPosCompensate + pointCAD(16)
                            ReturnXYR.Y5 += Pset(4).YPosCompensate + pointCAD(17)
                            ReturnXYR.X6 += Pset(5).XPosCompensate + pointCAD(18)
                            ReturnXYR.Y6 += Pset(5).YPosCompensate + pointCAD(19)
                            ReturnXYR.X7 += Pset(6).XPosCompensate + pointCAD(20)
                            ReturnXYR.Y7 += Pset(6).YPosCompensate + pointCAD(21)
                            ReturnXYR.X8 += Pset(7).XPosCompensate + pointCAD(22)
                            ReturnXYR.Y8 += Pset(7).YPosCompensate + pointCAD(23)
                            ReturnXYR.X9 += Pset(8).XPosCompensate + pointCAD(24)
                            ReturnXYR.Y9 += Pset(8).YPosCompensate + pointCAD(25)
                            ReturnXYR.X10 += Pset(9).XPosCompensate + pointCAD(26)
                            ReturnXYR.Y10 += Pset(9).YPosCompensate + pointCAD(27)
                            ReturnXYR.X11 += Pset(10).XPosCompensate + pointCAD(28)
                            ReturnXYR.Y11 += Pset(10).YPosCompensate + pointCAD(29)
                            ReturnXYR.X12 += Pset(11).XPosCompensate + pointCAD(30)
                            ReturnXYR.Y12 += Pset(11).YPosCompensate + pointCAD(31)
                            ReturnXYR.X13 += Pset(12).XPosCompensate + pointCAD(32)
                            ReturnXYR.Y13 += Pset(12).YPosCompensate + pointCAD(33)
                            ReturnXYR.X14 += Pset(13).XPosCompensate + pointCAD(34)
                            ReturnXYR.Y14 += Pset(13).YPosCompensate + pointCAD(35)
                            ReturnXYR.X15 += Pset(14).XPosCompensate + pointCAD(36)
                            ReturnXYR.Y15 += Pset(14).YPosCompensate + pointCAD(37)
                            ReturnXYR.X16 += Pset(15).XPosCompensate + pointCAD(38)
                            ReturnXYR.Y16 += Pset(15).YPosCompensate + pointCAD(39)
                            ReturnXYR.X17 += Pset(16).XPosCompensate + pointCAD(40)
                            ReturnXYR.Y17 += Pset(16).YPosCompensate + pointCAD(41)
                            ReturnXYR.X18 += Pset(17).XPosCompensate + pointCAD(42)
                            ReturnXYR.Y18 += Pset(17).YPosCompensate + pointCAD(43)
                            ReturnXYR.X19 += Pset(18).XPosCompensate + pointCAD(44)
                            ReturnXYR.Y19 += Pset(18).YPosCompensate + pointCAD(45)
                            ReturnXYR.X20 += Pset(19).XPosCompensate + pointCAD(46)
                            ReturnXYR.Y20 += Pset(19).YPosCompensate + pointCAD(47)
                            ReturnXYR.X21 += Pset(20).XPosCompensate + pointCAD(48)
                            ReturnXYR.Y21 += Pset(20).YPosCompensate + pointCAD(49)
                            ReturnXYR.X22 += Pset(21).XPosCompensate + pointCAD(50)
                            ReturnXYR.Y22 += Pset(21).YPosCompensate + pointCAD(51)
                            ReturnXYR.X23 += Pset(22).XPosCompensate + pointCAD(52)
                            ReturnXYR.Y23 += Pset(22).YPosCompensate + pointCAD(53)
                            ReturnXYR.X24 += Pset(23).XPosCompensate + pointCAD(54)
                            ReturnXYR.Y24 += Pset(23).YPosCompensate + pointCAD(55)
                            ReturnXYR.X25 += Pset(24).XPosCompensate + pointCAD(56)
                            ReturnXYR.Y25 += Pset(24).YPosCompensate + pointCAD(57)
                            ReturnXYR.X26 += Pset(25).XPosCompensate + pointCAD(58)
                            ReturnXYR.Y26 += Pset(25).YPosCompensate + pointCAD(59)
                            ReturnXYR.X27 += Pset(26).XPosCompensate + pointCAD(60)
                            ReturnXYR.Y27 += Pset(26).YPosCompensate + pointCAD(61)
                            ReturnXYR.X28 += Pset(27).XPosCompensate + pointCAD(62)
                            ReturnXYR.Y28 += Pset(27).YPosCompensate + pointCAD(63)
                            ReturnXYR.X29 += Pset(28).XPosCompensate + pointCAD(64)
                            ReturnXYR.Y29 += Pset(28).YPosCompensate + pointCAD(65)
                            ReturnXYR.X30 += Pset(29).XPosCompensate + pointCAD(66)
                            ReturnXYR.Y30 += Pset(29).YPosCompensate + pointCAD(67)

                            strSendData = Format(ReturnXYR.X1, "0.000") & "," & Format(ReturnXYR.Y1, "0.000") & "," & Format(pointCAD_Z(0), "0.000") & "," & Format(pointCAD_C(0), "0.000") & "," &
                                                                     Format(ReturnXYR.X2, "0.000") & "," & Format(ReturnXYR.Y2, "0.00") & "," & Format(pointCAD_Z(1), "0.00") & "," & Format(pointCAD_C(1), "0.000") & "," &
                                                                     Format(ReturnXYR.X3, "0.000") & "," & Format(ReturnXYR.Y3, "0.000") & "," & Format(pointCAD_Z(2), "0.000") & "," & Format(pointCAD_C(2), "0.000") & "," & vbCrLf

                            Dim byteSend1 As Byte() = Encoding.ASCII.GetBytes(Format(ReturnXYR.X1, "0.000") & "," & Format(ReturnXYR.Y1, "0.000") & "," & Format(pointCAD_Z(0), "0.000") & "," & Format(pointCAD_C(0), "0.000") & "," &
                                                                     Format(ReturnXYR.X2, "0.000") & "," & Format(ReturnXYR.Y2, "0.00") & "," & Format(pointCAD_Z(1), "0.00") & "," & Format(pointCAD_C(1), "0.000") & "," &
                                                                     Format(ReturnXYR.X3, "0.000") & "," & Format(ReturnXYR.Y3, "0.000") & "," & Format(pointCAD_Z(2), "0.000") & "," & Format(pointCAD_C(2), "0.000") & "," &
                                                                     Format(ReturnXYR.X4, "0.000") & "," & Format(ReturnXYR.Y4, "0.000") & "," & Format(pointCAD_Z(3), "0.000") & "," & Format(pointCAD_C(3), "0.000") & "," &
                                                                     Format(ReturnXYR.X5, "0.000") & "," & Format(ReturnXYR.Y5, "0.000") & "," & Format(pointCAD_Z(4), "0.000") & "," & Format(pointCAD_C(4), "0.000") & "," &
                                                                     Format(ReturnXYR.X6, "0.000") & "," & Format(ReturnXYR.Y6, "0.000") & "," & Format(pointCAD_Z(5), "0.000") & "," & Format(pointCAD_C(5), "0.000") & "," &
                                                                     Format(ReturnXYR.X7, "0.000") & "," & Format(ReturnXYR.Y7, "0.000") & "," & Format(pointCAD_Z(6), "0.000") & "," & Format(pointCAD_C(6), "0.000") & "," &
                                                                     Format(ReturnXYR.X8, "0.000") & "," & Format(ReturnXYR.Y8, "0.000") & "," & Format(pointCAD_Z(7), "0.000") & "," & Format(pointCAD_C(7), "0.000") & "," & vbCrLf)

                            Dim byteSend2 As Byte() = Encoding.ASCII.GetBytes(Format(ReturnXYR.X9, "0.000") & "," & Format(ReturnXYR.Y9, "0.000") & "," & Format(pointCAD_Z(8), "0.000") & "," & Format(pointCAD_C(8), "0.000") & "," &
                                                                      Format(ReturnXYR.X10, "0.000") & "," & Format(ReturnXYR.Y10, "0.000") & "," & Format(pointCAD_Z(9), "0.000") & "," & Format(pointCAD_C(9), "0.000") & "," &
                                                                      Format(ReturnXYR.X11, "0.000") & "," & Format(ReturnXYR.Y11, "0.000") & "," & Format(pointCAD_Z(10), "0.000") & "," & Format(pointCAD_C(10), "0.000") & "," &
                                                                      Format(ReturnXYR.X12, "0.000") & "," & Format(ReturnXYR.Y12, "0.000") & "," & Format(pointCAD_Z(11), "0.000") & "," & Format(pointCAD_C(11), "0.000") & "," &
                                                                      Format(ReturnXYR.X13, "0.000") & "," & Format(ReturnXYR.Y13, "0.000") & "," & Format(pointCAD_Z(12), "0.000") & "," & Format(pointCAD_C(12), "0.000") & "," &
                                                                      Format(ReturnXYR.X14, "0.000") & "," & Format(ReturnXYR.Y14, "0.000") & "," & Format(pointCAD_Z(13), "0.000") & "," & Format(pointCAD_C(13), "0.000") & "," &
                                                                      Format(ReturnXYR.X15, "0.000") & "," & Format(ReturnXYR.Y15, "0.000") & "," & Format(pointCAD_Z(14), "0.000") & "," & Format(pointCAD_C(14), "0.000") & "," & vbCrLf)

                            Dim byteSend3 As Byte() = Encoding.ASCII.GetBytes(Format(ReturnXYR.X16, "0.000") & "," & Format(ReturnXYR.Y16, "0.000") & "," & Format(pointCAD_Z(15), "0.000") & "," & Format(pointCAD_C(15), "0.000") & "," &
                                                                      Format(ReturnXYR.X17, "0.000") & "," & Format(ReturnXYR.Y17, "0.000") & "," & Format(pointCAD_Z(16), "0.000") & "," & Format(pointCAD_C(16), "0.000") & "," &
                                                                      Format(ReturnXYR.X18, "0.000") & "," & Format(ReturnXYR.Y18, "0.000") & "," & Format(pointCAD_Z(17), "0.000") & "," & Format(pointCAD_C(17), "0.000") & "," &
                                                                      Format(ReturnXYR.X19, "0.000") & "," & Format(ReturnXYR.Y19, "0.000") & "," & Format(pointCAD_Z(18), "0.000") & "," & Format(pointCAD_C(18), "0.000") & "," &
                                                                      Format(ReturnXYR.X20, "0.000") & "," & Format(ReturnXYR.Y20, "0.000") & "," & Format(pointCAD_Z(19), "0.000") & "," & Format(pointCAD_C(19), "0.000") & "," &
                                                                      Format(ReturnXYR.X21, "0.000") & "," & Format(ReturnXYR.Y21, "0.000") & "," & Format(pointCAD_Z(20), "0.000") & "," & Format(pointCAD_C(20), "0.000") & "," &
                                                                      Format(ReturnXYR.X22, "0.000") & "," & Format(ReturnXYR.Y22, "0.000") & "," & Format(pointCAD_Z(21), "0.000") & "," & Format(pointCAD_C(21), "0.000") & "," &
                                                                      Format(ReturnXYR.X23, "0.000") & "," & Format(ReturnXYR.Y23, "0.000") & "," & Format(pointCAD_Z(22), "0.000") & "," & Format(pointCAD_C(22), "0.000") & "," & vbCrLf)
                            Dim byteSend4 As Byte() = Encoding.ASCII.GetBytes(Format(ReturnXYR.X24, "0.000") & "," & Format(ReturnXYR.Y24, "0.000") & "," & Format(pointCAD_Z(23), "0.000") & "," & Format(pointCAD_C(23), "0.000") & "," &
                                                                     Format(ReturnXYR.X25, "0.000") & "," & Format(ReturnXYR.Y25, "0.000") & "," & Format(pointCAD_Z(24), "0.000") & "," & Format(pointCAD_C(24), "0.000") & "," &
                                                                     Format(ReturnXYR.X26, "0.000") & "," & Format(ReturnXYR.Y26, "0.000") & "," & Format(pointCAD_Z(25), "0.000") & "," & Format(pointCAD_C(25), "0.000") & "," &
                                                                     Format(ReturnXYR.X27, "0.000") & "," & Format(ReturnXYR.Y27, "0.000") & "," & Format(pointCAD_Z(26), "0.000") & "," & Format(pointCAD_C(26), "0.000") & "," &
                                                                     Format(ReturnXYR.X28, "0.000") & "," & Format(ReturnXYR.Y28, "0.000") & "," & Format(pointCAD_Z(27), "0.000") & "," & Format(pointCAD_C(27), "0.000") & "," &
                                                                     Format(ReturnXYR.X29, "0.000") & "," & Format(ReturnXYR.Y29, "0.000") & "," & Format(pointCAD_Z(28), "0.000") & "," & Format(pointCAD_C(28), "0.000") & "," &
                                                                     Format(ReturnXYR.X30, "0.000") & "," & Format(ReturnXYR.Y30, "0.000") & "," & Format(pointCAD_Z(29), "0.000") & "," & Format(pointCAD_C(29), "0.000") & "," & vbCrLf)

                            MySocket.Send(byteSend1)
                            waitstandby(100)
                            MySocket.Send(byteSend2)
                            If CurScrewPara.PointCount > 15 Then
                                waitstandby(100)
                                MySocket.Send(byteSend3)
                                waitstandby(100)
                                MySocket.Send(byteSend4)
                            End If
                            AppendInfoToTextBox(strSendData)
                            If ReturnXYR.X1 < 900 Or ReturnXYR.X1 < 900 Then
                                'Todaycount.PassCount += 1
                                'PassCount.Text = Todaycount.PassCount.ToString
                            Else
                                'log.WriteInfoTo_ResultLog_RichTextBox(RichTextBox_log, "第二个拍照点拍照失败", Color.Red)
                                'Todaycount.NGCount += 1
                                'NGCount.Text = Todaycount.NGCount.ToString
                                'TextBox_ErrMsg.AppendText("第二个拍照点拍照失败" + vbCrLf)

                                AppendInfoToTextBox("第二个拍照点拍照失败")
                            End If
                            TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"

                            CogRecordDisplay2.Image = tmpfifo0.OutputImage
                            CogRecordDisplay2.Fit()
                            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                CogRecordDisplay2.Record = tmpPmalign.CreateLastRunRecord
                            End If
                        Else
                            SecondCCDState = 3
                        End If

                    End If
                Else
                    SecondCCDState = 1
                End If
            Else
                SecondCCDState = 2
                GoTo c

            End If
        Catch ex As Exception
            MsgBox("SecondCameraImageProcess:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
d:
    End Sub

    Private Sub ThirdCameraImageProcess(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim __time As DateTime = DateTime.Now

        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(2).Tools.Item("相机设定")
            Dim tmpCalibCB As CogCalibCheckerboardTool = gTBCheck(2).Tools.Item("CogCalibCheckerboardTool1")
            'Dim tmpCalibCB As CogCalibNPointToNPointTool = gTBCheck(2).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpCogCalibCheckerboardTool As CogCalibNPointToNPointTool = gTBCheck(2).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpPmalign1 As CogPMAlignTool = gTBCheck(2).Tools.Item("CogPMAlignTool1")

            Dim tmpPmalign As CogPMAlignTool = tmpPmalign1
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim bHasObject As Boolean = False
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then

                If True Then
                    'If tmpfifo0.Operator.FrameGrabber.SerialNumber = SecondCCDSerNum Then
                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then

                        tmpfifo0.Run()
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        If tmpfifo0.OutputImage IsNot Nothing Then

                            SecondCCDState = 0 '正常
                            tmpCalibCB.Run()
                            tmpCogCalibCheckerboardTool.Run()
                            tmpPmalign1.Run()
                            Dim dTemp As Double = 0
                            Dim dTemp2 As String = ""

                            If tmpPmalign1.RunStatus.Result = CogToolResultConstants.Accept Then

                                If tmpPmalign.Results.Count > 0 Then
                                    SendDataX(3) = tmpPmalign.Results.Item(0).GetPose.TranslationX.ToString
                                    SendDataY(3) = tmpPmalign.Results.Item(0).GetPose.TranslationY.ToString
                                Else
                                    SendDataX(3) = 9999
                                    SendDataY(3) = 9999
                                End If
                                If tmpPmalign.Results.Count < 1 Then
                                    CogRecordDisplay3.Image = tmpfifo0.OutputImage
                                    Dim bmp As Bitmap = CogRecordDisplay3.Image.ToBitmap()
                                    If Directory.Exists(gVisionFailedPath & TCmbPro.Text & "\") = False Then  '判断文件夹是否存在
                                        Directory.CreateDirectory(gVisionFailedPath & TCmbPro.Text & "\")
                                    End If
                                    bmp.Save(gVisionFailedPath & TCmbPro.Text & "\" & Format(Date.Now.Date, "yyyyMMdd") & Format(DateTime.Now.Ticks) & ".bmp")
                                End If

c:
                                If SecondCCDState = 2 Then
                                    SendDataX(3) = 9999
                                    SendDataY(3) = 9999
                                End If
                            Else
                                SendDataX(3) = 9999
                                SendDataY(3) = 9999
                            End If

                            'Point_DateX(3) = photo_point(8) + SendDataX(3) + Pset(2).XPosCompensate
                            'Point_DateY(3) = photo_point(9) + SendDataY(3) + Pset(2).YPosCompensate
                            'Point_DateZ(3) = photo_point(10) + Pset(2).ZPosCompensate - CurScrewPara.chuansong_yanshi
                            'Point_DateR(3) = photo_point(11) + PointPara(3).angle

                            Point_DateX(3) = pointCAD_X(2) + SendDataX(3) + Pset(2).XPosCompensate
                            Point_DateY(3) = pointCAD_Y(2) + SendDataY(3) + Pset(2).YPosCompensate
                            Point_DateZ(3) = pointCAD_Z(2) + Pset(2).ZPosCompensate
                            Point_DateR(3) = pointCAD_C(2) + PointPara(3).angle

                            strSendData = Format(Point_DateX(3), "000.000") + "," + Format(Point_DateY(3), "000.000") + "," + Format(Point_DateZ(3), "000.000") + "," + Format(Point_DateR(3), "000.000")
                            strSendData += vbCrLf

                            Dim byteSend As Byte() = Encoding.ASCII.GetBytes(strSendData)
                            MySocket.Send(byteSend)

                            'log.WriteInfoTo_ResultLog_RichTextBox(RichTextBox_log, Format(SendDataX(3), "0.000") & "," & Format(SendDataY(3), "0.000") + vbCrLf)
                            'log.WriteInfoTo_ResultLog_RichTextBox(RichTextBox_log, strSendData)

                            AppendInfoToTextBox(Format(SendDataX(3), "0.000") & "," & Format(SendDataY(3), "0.000"))
                            AppendInfoToTextBox(strSendData)

                            If Point_DateX(3) < 900 Or Point_DateY(3) < 900 Then
                                'Todaycount.PassCount += 1
                                'PassCount.Text = Todaycount.PassCount.ToString
                            Else
                                'log.WriteInfoTo_ResultLog_RichTextBox(RichTextBox_log, "第三个拍照点拍照失败", Color.Red)
                                AppendInfoToTextBox("第三个拍照点拍照失败")
                                Todaycount.NGCount += 1
                                NGCount.Text = Todaycount.NGCount.ToString
                            End If
                            TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"

                            CogRecordDisplay3.Image = tmpfifo0.OutputImage
                            CogRecordDisplay3.Fit()
                            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                CogRecordDisplay3.Record = tmpPmalign.CreateLastRunRecord
                            End If
                        Else
                            SecondCCDState = 3
                        End If

                    End If
                Else
                    SecondCCDState = 1
                End If
            Else
                SecondCCDState = 2
                GoTo c

            End If
        Catch ex As Exception
            MsgBox("ThirdCameraImageProcess:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
d:
    End Sub

    Private Sub FourthCameraImageProcess(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim __time As DateTime = DateTime.Now
        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(2).Tools.Item("相机设定")
            'Dim tmpCalibCB As CogCalibCheckerboardTool = gTBCheck(2).Tools.Item("CogCalibCheckerboardTool1")
            'Dim tmpCogCalibCheckerboardTool As CogCalibNPointToNPointTool = gTBCheck(2).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpCog2DSymbolTool As Cog2DSymbolTool = gTBCheck(2).Tools.Item("Cog2DSymbolTool1")

            Dim tmpPmalign1 As Cog2DSymbolTool = tmpCog2DSymbolTool
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim bHasObject As Boolean = False
            Dim dTemp2 As String = ""

            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then

                If True Then

                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then

                        tmpfifo0.Run()

                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:

                        If tmpfifo0.OutputImage IsNot Nothing Then
                            SecondCCDState = 0 '正常

                            tmpPmalign1.Run()

                            If tmpPmalign1.RunStatus.Result = CogToolResultConstants.Accept Then

                                If tmpPmalign1.Result.Decoded = True Then
                                    dTemp2 = tmpPmalign1.Result.DecodedString.ToString
                                Else
                                    GoTo d

                                End If
c:
                            End If

                            If dTemp2 = "" Then

                                GoTo d
                            End If

                            CogRecordDisplay1.Image = tmpfifo0.OutputImage
                            CogRecordDisplay1.Fit()
                        Else
                            SecondCCDState = 3
                        End If

                    End If
                Else
                    SecondCCDState = 1
                End If
            Else
                SecondCCDState = 2
                GoTo c

            End If
        Catch ex As Exception
            MsgBox("FourthCameraImageProcess:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
d:
    End Sub

    ''' <summary>
    ''' CCD扫码使用
    ''' </summary>
    ''' <param name="MySocket"></param>
    ''' <param name="StrReceData"></param>
    ''' <remarks></remarks>
    Private Sub CCDcameraimagescancode(ByRef MySocket As Socket, ByVal StrReceData As String)
        Dim __time As DateTime = DateTime.Now
        AppendInfoToTextBox("ThirdCameraImageProcess")
        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(2).Tools.Item("相机设定")
            Dim tmpBarcode1 As CogIDTool = gTBCheck(2).Tools.Item("CogIDTool1")
            Dim tmpBarcode2 As CogIDTool = gTBCheck(2).Tools.Item("CogIDTool2")
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim SDFSFS As String = ""
            Dim bHasObject As Boolean = False
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                AppendInfoToTextBox("FrameGrabber")
                If True Then
                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Exception.ToString)
                        AppendInfoToTextBox(tmpfifo0.RunStatus.Message)
                        tmpfifo0.Run()
                        AppendInfoToTextBox("AcqBaseImage首次取相失败，再进行第二次取相")
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        CogRecordDisplay1.Image = tmpfifo0.OutputImage
                        CogRecordDisplay1.Fit()
                        If tmpfifo0.OutputImage IsNot Nothing Then
                            SecondCCDState = 0 '正常
                            AppendInfoToTextBox("tmpBarcode.Run()")
                            tmpBarcode1.Run()
                            tmpBarcode2.Run()
                            Dim ScanOk As Boolean = False
                            If ScanOk = False And tmpBarcode1.RunStatus.Result = CogToolResultConstants.Accept AndAlso tmpBarcode1.Results.Count > 0 Then
                                Dim barcode As String = tmpBarcode1.Results.Item(0).DecodedData.DecodedString              '扫码数据
                                AppendInfoToTextBox("相机1扫码条码：" & barcode)
                                ScanOk = ScanSNAndMESRequest(barcode, "")
                                If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                    CogRecordDisplay1.Record = tmpBarcode1.CreateLastRunRecord
                                End If
                            End If

                            If ScanOk = False And tmpBarcode2.RunStatus.Result = CogToolResultConstants.Accept AndAlso tmpBarcode2.Results.Count > 0 Then
                                Dim barcode As String = tmpBarcode2.Results.Item(0).DecodedData.DecodedString              '扫码数据
                                AppendInfoToTextBox("相机2扫码条码：" & barcode)
                                ScanOk = ScanSNAndMESRequest(barcode, "")
                                If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                    CogRecordDisplay1.Record = tmpBarcode2.CreateLastRunRecord
                                End If
                            End If
                            If ScanOk = False Then
                                AppendInfoToTextBox("相机扫码失败，保存图片")
                                Dim fileName As String = Format(Date.Now.Date, "yyyyMMdd") & Format(DateTime.Now.Ticks) & "扫码失败图片" & ".jpg"
                                Dim filePath As String = gVisionFailedPath & Format(Date.Now.Date, "yyyyMMdd") & "\" & Chanpin & "\" & "Fail Image\"
                                YSPic(CogRecordDisplay1, tmpfifo0, filePath, fileName)
                            End If
                        Else
c:
                            AppendInfoToTextBox("相机扫码失败")
                        End If
                        TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"
                    End If
                Else
                    AppendInfoToTextBox("相机扫码失败")
                End If
            Else
                AppendInfoToTextBox("相机扫码失败")
                AppendInfoToTextBox("未连接摄像机！")
            End If
        Catch ex As Exception
            WriteInspecLog(TSLog, "SecondCameraImageProcess" & vbTab & ex.StackTrace.ToString)
            AppendInfoToTextBox(ex.StackTrace.ToString)
        End Try
d:
    End Sub

    ''' <summary>
    ''' 压缩图片保存到指定文件夹下
    ''' </summary>
    ''' <param name="CogRecordDisplay"></param>
    ''' <param name="tmpfifo0"></param>
    ''' <param name="PicPath"></param>
    ''' <param name="PicName"></param>
    ''' <remarks></remarks>
    Private Sub YSPic(ByVal CogRecordDisplay As Cognex.VisionPro.CogRecordDisplay, ByVal tmpfifo0 As CogAcqFifoTool, ByVal PicPath As String, ByVal PicName As String)
        Try
            CogRecordDisplay.Image = tmpfifo0.OutputImage
            Dim codecs() As ImageCodecInfo = ImageCodecInfo.GetImageEncoders()
            Dim ici As ImageCodecInfo = Nothing
            Dim codec As ImageCodecInfo
            Dim compressPic1 As New Bitmap(CogRecordDisplay.Image.ToBitmap())
            Dim compressPic As Bitmap = New Bitmap(compressPic1)
            compressPic1.Dispose()
            Dim ep As EncoderParameters = New EncoderParameters()
            For Each codec In codecs
                If (codec.MimeType = "image/jpeg") Then
                    ici = codec
                End If
            Next
            '此处参数85代表压缩率，建议设置65-85之间， 范围0-100 ， 100代表图片质量最优，但压缩率最低
            ep.Param(0) = New EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85)
            If Directory.Exists(PicPath) = False Then  '判断文件夹是否存在
                Directory.CreateDirectory(PicPath)
            End If
            compressPic.Save(PicPath & PicName, ici, ep)
            compressPic.Dispose()
        Catch ex As Exception
            AppendInfoToTextBox("YSPic:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try

    End Sub

    Public Function TwoPointurn(ByVal x1, ByVal y1, ByVal x3, ByVal y3)
        '函数用法：20个输入参数，前六个是拍照点PMA工具传过来的偏移量。
        '所有参与的数据必须为同一坐标系。
        Dim xy As InputXY
        Dim returnxy As returnXY
        Dim L31, L31_, L41, L51, L61, L71, temp_returnX1, temp_returnY1, temp_returnR1 As Double
        Dim L81, L91, LA1, LB1, LC1, LD1, LE1, LF1, LG1, LH1, LI1, LJ1, LK1, LL1, LM1, LN1, LO1, LP1, LQ1, LR1, LS1, LT1, LU1, LV1, LW1, LX1 As Double
        Dim A41, A51, A61, A71, A81, A91, AA1, AB1, AC1, AD1, AE1, AF1, AG1, AH1, AI1, AJ1, AK1, AL1, AM1, AN1, AO1, AP1, AQ1, AR1, AS1, AT1, AU1, AV1, AW1, AX1 As Double
        Dim L1, L2, L3, L4, L5, L6 As Double
        Dim A1, A2, A3, A4, A5, A6 As Double
        Dim w, i As Integer

        For w = 0 To 69

        Next
        xy = New InputXY(pointCAD)

        L31 = Sqrt(Pow((xy.X03 - xy.X01), 2) + Pow((xy.y03 - xy.y01), 2))
        L31_ = Sqrt(Pow((xy.X03 + x3 - xy.X01 - x1), 2) + Pow((xy.y03 + y3 - xy.y01 - y1), 2))
        AppendInfoToTextBox("两点距离:" & Abs(L31 - L31_))

        If bzw = 1 Or bzw = 2 Then
            If Abs(L31 - L31_) > Pget(2).ZPosCompensate Then
                MsgBox("两点距离差值过大:" & Abs(L31 - L31_))
                AppendInfoToTextBox("两点距离差值过大:" & Abs(L31 - L31_))
                returnxy.X1 = 1000
                returnxy.Y1 = 1000
                returnxy.X2 = 1000
                returnxy.Y2 = 1000
                returnxy.X3 = 1000
                returnxy.Y3 = 1000
                returnxy.X4 = 1000
                returnxy.Y4 = 1000
                returnxy.X5 = 1000
                returnxy.Y5 = 1000
                returnxy.X6 = 1000
                returnxy.Y6 = 1000
                returnxy.X7 = 1000
                returnxy.Y7 = 1000
                returnxy.X8 = 1000
                returnxy.Y8 = 1000
                returnxy.X9 = 1000
                returnxy.Y9 = 1000
                returnxy.X10 = 1000
                returnxy.Y10 = 1000
                returnxy.X11 = 1000
                returnxy.Y11 = 1000
                returnxy.X12 = 1000
                returnxy.Y12 = 1000
                returnxy.X13 = 1000
                returnxy.Y13 = 1000
                returnxy.X14 = 1000
                returnxy.Y14 = 1000
                returnxy.X15 = 1000
                returnxy.Y15 = 1000
                returnxy.X16 = 1000
                returnxy.Y16 = 1000
                returnxy.X17 = 1000
                returnxy.Y17 = 1000
                returnxy.X18 = 1000
                returnxy.Y18 = 1000
                returnxy.X19 = 1000
                returnxy.Y19 = 1000
                returnxy.X20 = 1000
                returnxy.Y20 = 1000
                returnxy.X21 = 1000
                returnxy.Y21 = 1000
                returnxy.X22 = 1000
                returnxy.Y22 = 1000
                returnxy.X23 = 1000
                returnxy.Y23 = 1000
                returnxy.X24 = 1000
                returnxy.Y24 = 1000
                returnxy.X25 = 1000
                returnxy.Y25 = 1000
                returnxy.X26 = 1000
                returnxy.Y26 = 1000
                returnxy.X27 = 1000
                returnxy.Y27 = 1000
                returnxy.X28 = 1000
                returnxy.Y28 = 1000
                returnxy.X29 = 1000
                returnxy.Y29 = 1000
                returnxy.X30 = 1000
                returnxy.Y30 = 1000
                returnxy.X31 = 1000
                returnxy.Y31 = 1000
                returnxy.X32 = 1000
                returnxy.Y32 = 1000
                returnxy.X33 = 1000
                returnxy.Y33 = 1000
                returnxy.X34 = 1000
                returnxy.Y34 = 1000
                returnxy.X35 = 1000
                returnxy.Y35 = 1000
                returnxy.X36 = 1000
                returnxy.Y36 = 1000
                GoTo eend
            End If
        Else
            If Abs(L31 - L31_) > Pget(2).ZPosCompensate Or x1 < Pget(2).XPosCompensate Or x1 > Pget(2).YPosCompensate Or x3 < Pget(2).XPosCompensate Or x3 > Pget(2).YPosCompensate Then
                'ReturnXYR = TwoPointurn(SendDataX(0), SendDataY(0), SendDataX(2), SendDataY(2))
                AppendInfoToTextBox("X超出偏差范围" & ",第一个拍照点X=" & x1 & ",第二个拍照点X=" & x3 & "X偏差设定范围'" & Pget(2).XPosCompensate & "-" & Pget(2).YPosCompensate)
                returnxy.X1 = 1900
                returnxy.Y1 = 1900
                returnxy.X2 = 1900
                returnxy.Y2 = 1900
                returnxy.X3 = 1900
                returnxy.Y3 = 1900
                returnxy.X4 = 1900
                returnxy.Y4 = 1900
                returnxy.X5 = 1900
                returnxy.Y5 = 1900
                returnxy.X6 = 1900
                returnxy.Y6 = 1900
                returnxy.X7 = 1900
                returnxy.Y7 = 1900
                returnxy.X8 = 1900
                returnxy.Y8 = 1900
                returnxy.X9 = 1900
                returnxy.Y9 = 1900
                returnxy.X10 = 1900
                returnxy.Y10 = 1900
                returnxy.X11 = 1900
                returnxy.Y11 = 1900
                returnxy.X12 = 1900
                returnxy.Y12 = 1900
                returnxy.X13 = 1900
                returnxy.Y13 = 1900
                returnxy.X14 = 1900
                returnxy.Y14 = 1900
                returnxy.X15 = 1900
                returnxy.Y15 = 1900
                returnxy.X16 = 1900
                returnxy.Y16 = 1900
                returnxy.X17 = 1900
                returnxy.Y17 = 1900
                returnxy.X18 = 1900
                returnxy.Y18 = 1900
                returnxy.X19 = 1900
                returnxy.Y19 = 1900
                returnxy.X20 = 1900
                returnxy.Y20 = 1900
                returnxy.X21 = 1900
                returnxy.Y21 = 1900
                returnxy.X22 = 1900
                returnxy.Y22 = 1900
                returnxy.X23 = 1900
                returnxy.Y23 = 1900
                returnxy.X24 = 1900
                returnxy.Y24 = 1900
                returnxy.X25 = 1900
                returnxy.Y25 = 1900
                returnxy.X26 = 1900
                returnxy.Y26 = 1900
                returnxy.X27 = 1900
                returnxy.Y27 = 1900
                returnxy.X28 = 1900
                returnxy.Y28 = 1900
                returnxy.X29 = 1900
                returnxy.Y29 = 1900
                returnxy.X30 = 1900
                returnxy.Y30 = 1900
                returnxy.X31 = 1900
                returnxy.Y31 = 1900
                returnxy.X32 = 1900
                returnxy.Y32 = 1900
                returnxy.X33 = 1900
                returnxy.Y33 = 1900
                returnxy.X34 = 1900
                returnxy.Y34 = 1900
                returnxy.X35 = 1900
                returnxy.Y35 = 1900
                returnxy.X36 = 1900
                returnxy.Y36 = 1900
                GoTo eend
            End If
        End If
        L41 = Sqrt(Pow((xy.X04 - xy.X01), 2) + Pow((xy.y04 - xy.y01), 2))

        L51 = Sqrt(Pow((xy.X05 - xy.X01), 2) + Pow((xy.y05 - xy.y01), 2))

        L61 = Sqrt(Pow((xy.X06 - xy.X01), 2) + Pow((xy.y06 - xy.y01), 2))

        L71 = Sqrt(Pow((xy.X07 - xy.X01), 2) + Pow((xy.y07 - xy.y01), 2))

        L81 = Sqrt(Pow((xy.X08 - xy.X01), 2) + Pow((xy.y08 - xy.y01), 2))

        L91 = Sqrt(Pow((xy.X09 - xy.X01), 2) + Pow((xy.y09 - xy.y01), 2))

        LA1 = Sqrt(Pow((xy.X0A - xy.X01), 2) + Pow((xy.y0A - xy.y01), 2))

        LB1 = Sqrt(Pow((xy.X0B - xy.X01), 2) + Pow((xy.y0B - xy.y01), 2))

        LC1 = Sqrt(Pow((xy.X0C - xy.X01), 2) + Pow((xy.y0C - xy.y01), 2))

        LD1 = Sqrt(Pow((xy.X0D - xy.X01), 2) + Pow((xy.y0D - xy.y01), 2))

        LE1 = Sqrt(Pow((xy.X0E - xy.X01), 2) + Pow((xy.y0E - xy.y01), 2))

        LF1 = Sqrt(Pow((xy.X0F - xy.X01), 2) + Pow((xy.y0F - xy.y01), 2))

        LG1 = Sqrt(Pow((xy.X0G - xy.X01), 2) + Pow((xy.y0G - xy.y01), 2))

        LH1 = Sqrt(Pow((xy.X0H - xy.X01), 2) + Pow((xy.y0H - xy.y01), 2))

        LI1 = Sqrt(Pow((xy.X0I - xy.X01), 2) + Pow((xy.y0I - xy.y01), 2))

        LJ1 = Sqrt(Pow((xy.X0J - xy.X01), 2) + Pow((xy.y0J - xy.y01), 2))

        LK1 = Sqrt(Pow((xy.X0K - xy.X01), 2) + Pow((xy.y0K - xy.y01), 2))

        LL1 = Sqrt(Pow((xy.X0L - xy.X01), 2) + Pow((xy.y0L - xy.y01), 2))

        LM1 = Sqrt(Pow((xy.X0M - xy.X01), 2) + Pow((xy.y0M - xy.y01), 2))

        LN1 = Sqrt(Pow((xy.X0N - xy.X01), 2) + Pow((xy.y0N - xy.y01), 2))

        LO1 = Sqrt(Pow((xy.X0O - xy.X01), 2) + Pow((xy.y0O - xy.y01), 2))

        LP1 = Sqrt(Pow((xy.X0P - xy.X01), 2) + Pow((xy.y0P - xy.y01), 2))

        LQ1 = Sqrt(Pow((xy.X0Q - xy.X01), 2) + Pow((xy.y0Q - xy.y01), 2))

        LR1 = Sqrt(Pow((xy.X0R - xy.X01), 2) + Pow((xy.y0R - xy.y01), 2))

        LS1 = Sqrt(Pow((xy.X0S - xy.X01), 2) + Pow((xy.y0S - xy.y01), 2))

        LT1 = Sqrt(Pow((xy.X0T - xy.X01), 2) + Pow((xy.y0T - xy.y01), 2))

        LU1 = Sqrt(Pow((xy.X0U - xy.X01), 2) + Pow((xy.y0U - xy.y01), 2))

        LV1 = Sqrt(Pow((xy.X0V - xy.X01), 2) + Pow((xy.y0V - xy.y01), 2))

        LW1 = Sqrt(Pow((xy.X0W - xy.X01), 2) + Pow((xy.y0W - xy.y01), 2))

        LX1 = Sqrt(Pow((xy.X0X - xy.X01), 2) + Pow((xy.y0X - xy.y01), 2))

        L1 = Sqrt(Pow((xy.X11 - xy.X01), 2) + Pow((xy.y11 - xy.y01), 2))       '增加liu个数据
        L2 = Sqrt(Pow((xy.X22 - xy.X01), 2) + Pow((xy.y22 - xy.y01), 2))
        L3 = Sqrt(Pow((xy.X33 - xy.X01), 2) + Pow((xy.y33 - xy.y01), 2))
        L4 = Sqrt(Pow((xy.X44 - xy.X01), 2) + Pow((xy.y44 - xy.y01), 2))
        L5 = Sqrt(Pow((xy.X55 - xy.X01), 2) + Pow((xy.y55 - xy.y01), 2))
        L6 = Sqrt(Pow((xy.X66 - xy.X01), 2) + Pow((xy.y66 - xy.y01), 2))

        temp_returnR1 = Atan2((xy.y01 - xy.y03), (xy.X01 - xy.X03)) - Atan2(((y1 + xy.y01) - (y3 + xy.y03)), ((x1 + xy.X01) - (x3 + xy.X03)))

        '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

        A41 = Atan2((xy.y04 - xy.y01), (xy.X04 - xy.X01)) - temp_returnR1

        A51 = Atan2((xy.y05 - xy.y01), (xy.X05 - xy.X01)) - temp_returnR1

        A61 = Atan2((xy.y06 - xy.y01), (xy.X06 - xy.X01)) - temp_returnR1

        A71 = Atan2((xy.y07 - xy.y01), (xy.X07 - xy.X01)) - temp_returnR1

        A81 = Atan2((xy.y08 - xy.y01), (xy.X08 - xy.X01)) - temp_returnR1

        A91 = Atan2((xy.y09 - xy.y01), (xy.X09 - xy.X01)) - temp_returnR1

        AA1 = Atan2((xy.y0A - xy.y01), (xy.X0A - xy.X01)) - temp_returnR1

        AB1 = Atan2((xy.y0B - xy.y01), (xy.X0B - xy.X01)) - temp_returnR1

        AC1 = Atan2((xy.y0C - xy.y01), (xy.X0C - xy.X01)) - temp_returnR1

        AD1 = Atan2((xy.y0D - xy.y01), (xy.X0D - xy.X01)) - temp_returnR1

        AE1 = Atan2((xy.y0E - xy.y01), (xy.X0E - xy.X01)) - temp_returnR1

        AF1 = Atan2((xy.y0F - xy.y01), (xy.X0F - xy.X01)) - temp_returnR1

        AG1 = Atan2((xy.y0G - xy.y01), (xy.X0G - xy.X01)) - temp_returnR1

        AH1 = Atan2((xy.y0H - xy.y01), (xy.X0H - xy.X01)) - temp_returnR1

        AI1 = Atan2((xy.y0I - xy.y01), (xy.X0I - xy.X01)) - temp_returnR1

        AJ1 = Atan2((xy.y0J - xy.y01), (xy.X0J - xy.X01)) - temp_returnR1

        AK1 = Atan2((xy.y0K - xy.y01), (xy.X0K - xy.X01)) - temp_returnR1

        AL1 = Atan2((xy.y0L - xy.y01), (xy.X0L - xy.X01)) - temp_returnR1

        AM1 = Atan2((xy.y0M - xy.y01), (xy.X0M - xy.X01)) - temp_returnR1

        AN1 = Atan2((xy.y0N - xy.y01), (xy.X0N - xy.X01)) - temp_returnR1

        AO1 = Atan2((xy.y0O - xy.y01), (xy.X0O - xy.X01)) - temp_returnR1

        AP1 = Atan2((xy.y0P - xy.y01), (xy.X0P - xy.X01)) - temp_returnR1

        AQ1 = Atan2((xy.y0Q - xy.y01), (xy.X0Q - xy.X01)) - temp_returnR1

        AR1 = Atan2((xy.y0R - xy.y01), (xy.X0R - xy.X01)) - temp_returnR1

        AS1 = Atan2((xy.y0S - xy.y01), (xy.X0S - xy.X01)) - temp_returnR1

        AT1 = Atan2((xy.y0T - xy.y01), (xy.X0T - xy.X01)) - temp_returnR1

        AU1 = Atan2((xy.y0U - xy.y01), (xy.X0U - xy.X01)) - temp_returnR1

        AV1 = Atan2((xy.y0V - xy.y01), (xy.X0V - xy.X01)) - temp_returnR1

        AW1 = Atan2((xy.y0W - xy.y01), (xy.X0W - xy.X01)) - temp_returnR1

        AX1 = Atan2((xy.y0X - xy.y01), (xy.X0X - xy.X01)) - temp_returnR1

        A1 = Atan2((xy.y11 - xy.y01), (xy.X11 - xy.X01)) - temp_returnR1          '增加6个数据
        A2 = Atan2((xy.y22 - xy.y01), (xy.X22 - xy.X01)) - temp_returnR1
        A3 = Atan2((xy.y33 - xy.y01), (xy.X33 - xy.X01)) - temp_returnR1
        A4 = Atan2((xy.y44 - xy.y01), (xy.X44 - xy.X01)) - temp_returnR1
        A5 = Atan2((xy.y55 - xy.y01), (xy.X55 - xy.X01)) - temp_returnR1
        A6 = Atan2((xy.y66 - xy.y01), (xy.X66 - xy.X01)) - temp_returnR1
        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

        temp_returnX1 = x1 + xy.X01 - xy.X04 + L41 * Cos(A41)

        temp_returnY1 = y1 + xy.y01 - xy.y04 + L41 * Sin(A41)

        returnxy.X1 = temp_returnX1
        returnxy.Y1 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X05 + L51 * Cos(A51)

        temp_returnY1 = y1 + xy.y01 - xy.y05 + L51 * Sin(A51)

        returnxy.X2 = temp_returnX1
        returnxy.Y2 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X06 + L61 * Cos(A61)

        temp_returnY1 = y1 + xy.y01 - xy.y06 + L61 * Sin(A61)

        returnxy.X3 = temp_returnX1
        returnxy.Y3 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X07 + L71 * Cos(A71)

        temp_returnY1 = y1 + xy.y01 - xy.y07 + L71 * Sin(A71)

        returnxy.X4 = temp_returnX1
        returnxy.Y4 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X08 + L81 * Cos(A81)

        temp_returnY1 = y1 + xy.y01 - xy.y08 + L81 * Sin(A81)

        returnxy.X5 = temp_returnX1
        returnxy.Y5 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X09 + L91 * Cos(A91)

        temp_returnY1 = y1 + xy.y01 - xy.y09 + L91 * Sin(A91)

        returnxy.X6 = temp_returnX1
        returnxy.Y6 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0A + LA1 * Cos(AA1)

        temp_returnY1 = y1 + xy.y01 - xy.y0A + LA1 * Sin(AA1)

        returnxy.X7 = temp_returnX1
        returnxy.Y7 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0B + LB1 * Cos(AB1)

        temp_returnY1 = y1 + xy.y01 - xy.y0B + LB1 * Sin(AB1)

        returnxy.X8 = temp_returnX1
        returnxy.Y8 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0C + LC1 * Cos(AC1)

        temp_returnY1 = y1 + xy.y01 - xy.y0C + LC1 * Sin(AC1)

        returnxy.X9 = temp_returnX1
        returnxy.Y9 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0D + LD1 * Cos(AD1)

        temp_returnY1 = y1 + xy.y01 - xy.y0D + LD1 * Sin(AD1)

        returnxy.X10 = temp_returnX1
        returnxy.Y10 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0E + LE1 * Cos(AE1)

        temp_returnY1 = y1 + xy.y01 - xy.y0E + LE1 * Sin(AE1)

        returnxy.X11 = temp_returnX1
        returnxy.Y11 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0F + LF1 * Cos(AF1)

        temp_returnY1 = y1 + xy.y01 - xy.y0F + LF1 * Sin(AF1)

        returnxy.X12 = temp_returnX1
        returnxy.Y12 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0G + LG1 * Cos(AG1)

        temp_returnY1 = y1 + xy.y01 - xy.y0G + LG1 * Sin(AG1)

        returnxy.X13 = temp_returnX1
        returnxy.Y13 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0H + LH1 * Cos(AH1)

        temp_returnY1 = y1 + xy.y01 - xy.y0H + LH1 * Sin(AH1)

        returnxy.X14 = temp_returnX1
        returnxy.Y14 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0I + LI1 * Cos(AI1)

        temp_returnY1 = y1 + xy.y01 - xy.y0I + LI1 * Sin(AI1)

        returnxy.X15 = temp_returnX1
        returnxy.Y15 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0J + LJ1 * Cos(AJ1)

        temp_returnY1 = y1 + xy.y01 - xy.y0J + LJ1 * Sin(AJ1)

        returnxy.X16 = temp_returnX1
        returnxy.Y16 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0K + LK1 * Cos(AK1)

        temp_returnY1 = y1 + xy.y01 - xy.y0K + LK1 * Sin(AK1)

        returnxy.X17 = temp_returnX1
        returnxy.Y17 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0L + LL1 * Cos(AL1)

        temp_returnY1 = y1 + xy.y01 - xy.y0L + LL1 * Sin(AL1)

        returnxy.X18 = temp_returnX1
        returnxy.Y18 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0M + LM1 * Cos(AM1)

        temp_returnY1 = y1 + xy.y01 - xy.y0M + LM1 * Sin(AM1)

        returnxy.X19 = temp_returnX1
        returnxy.Y19 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0N + LN1 * Cos(AN1)

        temp_returnY1 = y1 + xy.y01 - xy.y0N + LN1 * Sin(AN1)

        returnxy.X20 = temp_returnX1
        returnxy.Y20 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0O + LO1 * Cos(AO1)

        temp_returnY1 = y1 + xy.y01 - xy.y0O + LO1 * Sin(AO1)

        returnxy.X21 = temp_returnX1
        returnxy.Y21 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0P + LP1 * Cos(AP1)

        temp_returnY1 = y1 + xy.y01 - xy.y0P + LP1 * Sin(AP1)

        returnxy.X22 = temp_returnX1
        returnxy.Y22 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0Q + LQ1 * Cos(AQ1)

        temp_returnY1 = y1 + xy.y01 - xy.y0Q + LQ1 * Sin(AQ1)

        returnxy.X23 = temp_returnX1
        returnxy.Y23 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0R + LR1 * Cos(AR1)

        temp_returnY1 = y1 + xy.y01 - xy.y0R + LR1 * Sin(AR1)

        returnxy.X24 = temp_returnX1
        returnxy.Y24 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0S + LS1 * Cos(AS1)

        temp_returnY1 = y1 + xy.y01 - xy.y0S + LS1 * Sin(AS1)

        returnxy.X25 = temp_returnX1
        returnxy.Y25 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0T + LT1 * Cos(AT1)

        temp_returnY1 = y1 + xy.y01 - xy.y0T + LT1 * Sin(AT1)

        returnxy.X26 = temp_returnX1
        returnxy.Y26 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0U + LU1 * Cos(AU1)

        temp_returnY1 = y1 + xy.y01 - xy.y0U + LU1 * Sin(AU1)

        returnxy.X27 = temp_returnX1
        returnxy.Y27 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0V + LV1 * Cos(AV1)
        temp_returnY1 = y1 + xy.y01 - xy.y0V + LV1 * Sin(AV1)

        returnxy.X28 = temp_returnX1
        returnxy.Y28 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0W + LW1 * Cos(AW1)
        temp_returnY1 = y1 + xy.y01 - xy.y0W + LW1 * Sin(AW1)

        returnxy.X29 = temp_returnX1
        returnxy.Y29 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X0X + LX1 * Cos(AX1)

        temp_returnY1 = y1 + xy.y01 - xy.y0X + LX1 * Sin(AX1)

        returnxy.X30 = temp_returnX1
        returnxy.Y30 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X11 + L1 * Cos(A1)    '增加点位
        temp_returnY1 = y1 + xy.y01 - xy.y11 + L1 * Sin(A1)

        returnxy.X31 = temp_returnX1
        returnxy.Y31 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X22 + L2 * Cos(A2)
        temp_returnY1 = y1 + xy.y01 - xy.y22 + L2 * Sin(A2)

        returnxy.X32 = temp_returnX1
        returnxy.Y32 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X33 + L3 * Cos(A3)
        temp_returnY1 = y1 + xy.y01 - xy.y33 + L3 * Sin(A3)

        returnxy.X33 = temp_returnX1
        returnxy.Y33 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X44 + L4 * Cos(A4)
        temp_returnY1 = y1 + xy.y01 - xy.y44 + L4 * Sin(A4)

        returnxy.X34 = temp_returnX1
        returnxy.Y34 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X55 + L5 * Cos(A5)
        temp_returnY1 = y1 + xy.y01 - xy.y55 + L5 * Sin(A5)

        returnxy.X35 = temp_returnX1
        returnxy.Y35 = temp_returnY1

        temp_returnX1 = x1 + xy.X01 - xy.X66 + L6 * Cos(A6)
        temp_returnY1 = y1 + xy.y01 - xy.y66 + L6 * Sin(A6)

        returnxy.X36 = temp_returnX1
        returnxy.Y36 = temp_returnY1

eend:
        Dim Q As Integer
        For Q = 0 To 71
            resu(Q) = returnxy.read()(Q)
        Next
        bzw = 0
over:
        Return returnxy

    End Function

    Private Sub RobotParameterSet(ByRef MySocket As Socket, ByVal StrReceData As String)
        'Dim strSendData As String = ""
        'strSendData += CStr(Pget(0).XPosCompensate) + "," + CStr(Pget(0).YPosCompensate) + "," + CStr(Pget(0).ZPosCompensate) + ","
        'strSendData += CStr(Pget(1).XPosCompensate) + "," + CStr(Pget(1).YPosCompensate) + "," + CStr(Pget(1).ZPosCompensate) + ","
        'strSendData += CStr(CurScrewPara.Online_Mod) + "," + CStr(Pget(6).YPosCompensate) + "," & "," & newset(8)

        'AppendInfoToTextBox("send:" & vbCrLf + Chanpin + "," + strSendData + vbCrLf)

        'strSendData += vbCrLf
        'Dim byteSend As Byte() = Encoding.ASCII.GetBytes(Chanpin + "," + strSendData)
        'MySocket.Send(byteSend)

        Dim strSendData As String = ""
        strSendData += CStr(Pget(0).XPosCompensate) + "," + CStr(Pget(0).YPosCompensate) + "," + CStr(Pget(0).ZPosCompensate) + ","
        strSendData += CStr(Pget(1).XPosCompensate) + "," + CStr(Pget(1).YPosCompensate) + "," + CStr(Pget(1).ZPosCompensate) + ","
        strSendData += CStr(newset(0)) + "," + CStr(newset(1)) + "," + CStr(ADD_Screw_Count) + "," + CStr(CurScrewPara.PointCount) + ","
        strSendData += CStr(CurScrewPara.Online_Mod) + "," + CStr(Pget(6).YPosCompensate) + "," & "False" 'newset(8)
        AppendInfoToTextBox("send:" + Chanpin + "," + strSendData)

        strSendData += vbCrLf
        Dim byteSend As Byte() = Encoding.ASCII.GetBytes(Chanpin + "," + strSendData)
        MySocket.Send(byteSend)

    End Sub

#End Region

    Private Sub 产品管理ProductToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 产品管理ProductToolStripMenuItem.Click
        FrmProduct.ShowDialog()
    End Sub

    Private Sub 退出ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 退出ExitToolStripMenuItem.Click
        AppendInfoToTextBox("点击退出")
        Me.Close()
    End Sub

    Private Sub 登陆LoginToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 登陆LoginToolStripMenuItem.Click
        If gPriority = 0 Then
            FrmAdmin.ShowDialog()
        Else
            MsgBox("人员已登陆, 请先登出!")
        End If
    End Sub

    Private Sub 登出LogoutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 登出LogoutToolStripMenuItem.Click
        gPriority = 0
        TextBox_OPID.Text = "未登录"
        TextBox_OPID.BackColor = Color.WhiteSmoke
        FrmAdmin.EnableMenu()
    End Sub

    Private Sub 参数设置ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 参数设置ToolStripMenuItem.Click
        If machineInfo.ConfigMustLogin = "1" Then
            Dim result As DialogResult = FrmUserPad.ShowDialog()
            If result = DialogResult.Cancel Then
                Return
            End If
            If G_AdminPwd = "" Then
                Return
            End If
            If G_AdminPwd <> "123" Then
                MsgBox("密码错误")
                Return
            End If
        End If

        ParameterSet.ShowDialog()
    End Sub

    Private Sub 设备信息设置ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 设备信息设置ToolStripMenuItem.Click
        FrmEquipment.ShowDialog()
    End Sub

    Private Sub 关于本程序ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 关于本程序ToolStripMenuItem.Click
        FrmAbout.ShowDialog()
    End Sub

    Private Sub ToolStripButton17_Click(sender As Object, e As EventArgs) Handles ToolStripButton17.Click
        If TCmbPro.Text <> "" Then
            initPro(TCmbPro.Text)
            InitSetting()
        Else
            MsgBox("请先选择产品！")
        End If
    End Sub

    Public Sub initPro(ByVal ProName As String) '初始化产品参数
        Try
            GetXML()
            TSProcessLoad.Value = 0
            Dim path As String = gProDataPath & "\" & ProName & "\"
            Dim i As Integer
            For i = 0 To Cam_num - 1
                gTBCheck(i) = Nothing
                gTBCheck(i) = New CogToolBlock
            Next
            If Dir(path, FileAttribute.Directory) <> "" Then '如果路径存在
                For i = 0 To Cam_num - 1
                    gTBCheck(i) = CogSerializer.LoadObjectFromFile(path & "TBCheck" & (i + 1).ToString & ".vpp")
                    gTBCheck(i).LastRunRecordEnable = Cognex.VisionPro.Implementation.Internal.CogUserToolLastRunRecordConstants.CompositeSubToolRecords
                    fifo(i) = gTBCheck(i).Tools.Item("相机设定")
                    TSProcessLoad.Value += Int(100 / Cam_num)
                    Select Case i
                        Case 0
                            OPC_Machine_Parameter.Photo1_Exposure = fifo(i).Operator.OwnedExposureParams.Exposure
                        Case 1
                            OPC_Machine_Parameter.Photo2_Exposure = fifo(i).Operator.OwnedExposureParams.Exposure
                        Case 2
                            OPC_Machine_Parameter.Photo3_Exposure = fifo(i).Operator.OwnedExposureParams.Exposure
                    End Select
                Next
                TSLog.Text = vbTab & ProName & "加载产品完成"
                AppendInfoToTextBox(ProName + "加载产品完成")
                Dim WX As String = TSLog.Text
                Dim WJX() As String = WX.Split(vbTab)
                SaveSetting("XCPro", "Settings", "当前产品", ProName)
                'Me.Text = "视觉检测系统---" & ProName
                Me.Text = "视觉检测系统"
                GetDirectFiles(gProDataPath)
                TCmbPro.SelectedItem = ProName
                Chanpin = ProName
                '数据上传
                DataByPCS.Program = Chanpin
                DataByReal.Program = Chanpin
                DataByReal.Model = Chanpin
                CurNameAndSN.ChanpinName = Chanpin
                CurNameAndSN.ChanpinSN = NewNameAndSN.ChanpinSN 'SN扫码
                DataByPCS.USN = CurNameAndSN.ChanpinSN
            Else
                TSLog.Text = "加载产品路径不存在"
                AppendInfoToTextBox("加载产品路径不存在")
            End If
            ToolStripButton17.Enabled = True
            TSProcessLoad.Value = 0
        Catch ex As Exception
            MsgBox("初始化加载产品出错!" & ex.Message)
            ToolStripButton17.Enabled = True
        End Try
    End Sub

    Public Sub initTool() '初始化使用的工具
        Try
            GetDirectFiles(gProDataPath)
            Dim i As Integer
            TSProcessLoad.Value = 0
            For i = 0 To Cam_num - 1
                gTBCheck(i) = New CogToolBlock
                fifo(i) = New CogAcqFifoTool
            Next
            For i = 0 To Cam_num - 1
                gTBCheck(i) = CogSerializer.LoadObjectFromFile(gProDataPath & "TBCheck" & (i + 1).ToString & ".vpp")
                gTBCheck(i).LastRunRecordEnable = Cognex.VisionPro.Implementation.Internal.CogUserToolLastRunRecordConstants.CompositeSubToolRecords
                fifo(i) = gTBCheck(i).Tools.Item("相机设定")
            Next
        Catch ex As Exception
            MsgBox("初始化图像处理参数失败!" & ex.Message)
        End Try
    End Sub

    Private Sub GetDirectFiles(ByVal s As String)
        '找出位于 s 根目录下的所有文件
        Dim f() As String
        Try
            Dim i As Integer
            Dim t As Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.FileSystem.GetFiles(s), k As String, name() As String
            ' Me.Text = s
            Me.TCmbPro.Items.Clear()
            For Each k In My.Computer.FileSystem.GetDirectories(s)
                ReDim Preserve f(i)
                f(i) = k
                If 1 Then
                    Dim myFileInfo As New IO.FileInfo(f(i))
                    name = Split(f(i), "\")
                    ' f(i) = Right(f(i), f(i).Length - name.Length)
                    'C1FlexGrid1.Item(i + 1, 2) = name(UBound(name)) '获取文件名
                    'C1FlexGrid1.Item(i + 1, 3) = myFileInfo.LastWriteTime '获取文件名
                    Me.TCmbPro.Items.Add(name(name.Length - 1))
                End If
                i += 1
            Next
            TCmbPro.SelectedItem = gCurrProName
        Catch ex As Exception
            MsgBox("GetDirectFiles" & ex.Message)
        End Try
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        FolderBrowserDialog1.ShowDialog()
        gVisionFailedPath = FolderBrowserDialog1.SelectedPath
        If Microsoft.VisualBasic.Right(gVisionFailedPath, 1) <> "\" Then
            gVisionFailedPath += "\"
        End If
        TextBox4.Text = gVisionFailedPath
        SaveSetting("XCPro", "Settings", "VisionFailedPath", gVisionFailedPath)
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        TabControl1.SelectedIndex = 1
        Dim appwin As IntPtr
        Dim Process As Process
        Try
            Process = System.Diagnostics.Process.Start(exeName)
            Process.WaitForInputIdle()
            appwin = Process.MainWindowHandle
            System.Threading.Thread.Sleep(100)
        Catch ex As Exception
            MessageBox.Show(Me, ex.Message, "Error")
        End Try
        SetParent(appwin, Me.Panel1.Handle)
        MoveWindow(appwin, 0, 0, Me.Width, Me.Height, True)
        Timer1.Enabled = True
        SetCursorPos(550, 280)
        mouse_event(&H2, 0, 0, 0, 0) '鼠标左键按下
        mouse_event(&H4, 0, 0, 0, 0) '鼠标左键弹
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Try
            Dim lngCalculator As IntPtr
            Dim lngStyle As Long
            lngCalculator = FindWindow(vbNullString, "螺丝机_V2_1_4_3_人机应用_1")
            If lngCalculator Then
                SetParent(lngCalculator, Me.Panel1.Handle)
                lngStyle = FindWindow(vbNullString, "螺丝机_V2_1_4_3_人机应用_1")
                '       SetWindowLong(lngStyle, GWL_EXSTYLE, WS_EX_MDICHILD)
                MoveWindow(lngCalculator, -78, -98, 870, 580, 1)
                'Panel1.Size = New Size(800, 480)
                TabControl1.SelectedIndex = 0
                Timer1.Enabled = False
            End If
        Catch ex As Exception

        End Try

    End Sub

    Private Sub Count_Clear_Click(sender As Object, e As EventArgs)
        Todaycount.NGCount = 0
        Todaycount.PassCount = 0
        Todaycount.SCount = 0
        Todaycount.ScrewCount = 0
        Todaycount.ScrewFailed1 = 0
        Todaycount.ScrewFailed2 = 0
        Todaycount.ScrewFailed3 = 0
        Todaycount.ScrewFailed4 = 0
        Todaycount.ScrewFailed5 = 0
        Todaycount.ScrewFailed6 = 0
        Todaycount.ScrewFailed7 = 0
        Todaycount.ScrewFailed8 = 0
        Todaycount.ScrewFailed9 = 0
        Todaycount.ScrewFailed10 = 0
        Todaycount.ScrewFailed11 = 0
        Todaycount.ScrewFailed12 = 0
        Todaycount.ScrewFailed13 = 0
        Todaycount.ScrewFailed14 = 0
        Todaycount.ScrewFailed15 = 0
        Todaycount.ScrewFailed16 = 0
        Todaycount.ScrewFailed17 = 0
        Todaycount.ScrewFailed18 = 0
        Todaycount.ScrewFailed19 = 0
        Todaycount.ScrewFailed20 = 0
        Todaycount.ScrewFailed21 = 0
        Todaycount.ScrewFailed22 = 0
        Todaycount.ScrewFailed23 = 0
        Todaycount.ScrewFailed24 = 0
        Todaycount.ScrewFailed25 = 0
        Todaycount.ScrewFailed26 = 0
        Todaycount.ScrewFailed27 = 0
        Todaycount.ScrewFailed28 = 0
        Todaycount.ScrewFailed29 = 0
        Todaycount.ScrewFailed30 = 0

        Todaycount.ScrewFailed31 = 0
        Todaycount.ScrewFailed32 = 0
        Todaycount.ScrewFailed33 = 0
        Todaycount.ScrewFailed34 = 0
        Todaycount.ScrewFailed35 = 0
        Todaycount1.SNCount = 0
        Todaycount1.SN_Check = 0

        ScrewCount.Text = Todaycount.ScrewCount.ToString
        PassCount.Text = Todaycount.PassCount.ToString
        NGCount.Text = Todaycount.NGCount.ToString
        SCount.Text = Todaycount.SCount.ToString
        TextBox7.Text = "100.00 %"
        ScrewFailed1.Text = Todaycount.ScrewFailed1.ToString
        ScrewFailed2.Text = Todaycount.ScrewFailed2.ToString
        ScrewFailed3.Text = Todaycount.ScrewFailed3.ToString
        ScrewFailed4.Text = Todaycount.ScrewFailed4.ToString
        ScrewFailed5.Text = Todaycount.ScrewFailed5.ToString
        ScrewFailed6.Text = Todaycount.ScrewFailed6.ToString
        ScrewFailed7.Text = Todaycount.ScrewFailed7.ToString
        ScrewFailed8.Text = Todaycount.ScrewFailed8.ToString
        ScrewFailed9.Text = Todaycount.ScrewFailed9.ToString
        ScrewFailed10.Text = Todaycount.ScrewFailed10.ToString
        ScrewFailed11.Text = Todaycount.ScrewFailed11.ToString
        ScrewFailed12.Text = Todaycount.ScrewFailed12.ToString
        ScrewFailed13.Text = Todaycount.ScrewFailed13.ToString
        ScrewFailed14.Text = Todaycount.ScrewFailed14.ToString
        ScrewFailed15.Text = Todaycount.ScrewFailed15.ToString
        ScrewFailed16.Text = Todaycount.ScrewFailed16.ToString
        ScrewFailed17.Text = Todaycount.ScrewFailed17.ToString
        ScrewFailed18.Text = Todaycount.ScrewFailed18.ToString
        ScrewFailed19.Text = Todaycount.ScrewFailed19.ToString
        ScrewFailed20.Text = Todaycount.ScrewFailed20.ToString
        ScrewFailed21.Text = Todaycount.ScrewFailed21.ToString
        ScrewFailed22.Text = Todaycount.ScrewFailed22.ToString
        ScrewFailed23.Text = Todaycount.ScrewFailed23.ToString
        ScrewFailed24.Text = Todaycount.ScrewFailed24.ToString
        ScrewFailed25.Text = Todaycount.ScrewFailed25.ToString
        ScrewFailed26.Text = Todaycount.ScrewFailed26.ToString
        ScrewFailed27.Text = Todaycount.ScrewFailed27.ToString
        ScrewFailed28.Text = Todaycount.ScrewFailed28.ToString
        ScrewFailed29.Text = Todaycount.ScrewFailed29.ToString
        ScrewFailed30.Text = Todaycount.ScrewFailed30.ToString
        TxtBlowNum.Text = Todaycount.ScrewFailed35.ToString
        '新增异常台数、cycle time
        Todaycount.PCSFailedCount = 0
        Todaycount.CycleTime = 0
        Todaycount.SuctionCount = 0
        TextBox_CT.Text = Todaycount.CycleTime.ToString
        TextBox_Yield.Text = "100.00 %"
        TextBox_PCSFailed.Text = Todaycount.PCSFailedCount.ToString
        SuctionCount.Text = 0
        IsFirstSend = 1
        ''''''''''
        If Exists(gProDataPath & "\count.txt") Then
            '      Kill(filepath & TCmbPro.Text & "\count.txt")
            FileOpen(file_num_count, gProDataPath & "\count.txt", OpenMode.Random, , , RecordLength:=Len(Todaycount))
            FilePut(file_num_count, Todaycount)
            FileClose(file_num_count)
        End If

        If Exists(gProDataPath & "\count1.txt") Then
            '      Kill(filepath & TCmbPro.Text & "\count.txt")
            FileOpen(file_num_count1, gProDataPath & "\count1.txt", OpenMode.Random, , , RecordLength:=Len(Todaycount))
            FilePut(file_num_count1, Todaycount1)
            FileClose(file_num_count1)
        End If

    End Sub

#Region "查询生产报表"""

    Private Sub SaveDeviation(ByVal dateTime As String, ByVal proCount As String, ByVal XH As String, ByVal NL As String, ByVal ScrewTime As String, ByVal ScrewQS As String, ByVal result As String)

        'Test_Date_deleted() '''''''''''删除过期生产数据
        Try
            'Dim sql As String = "insert into ProInfo(日期,当日数量,产品型号,锁附扭力,时间,圈数,结果) values(" & "'" & dateTime & "'" & "," & "'" & proCount & "'" & "," & "'" & XH & "'" & "," & "'" & NL & "'" & "," & "'" & ScrewTime & "'" & "," & "'" & ScrewQS & "'" & "," & "'" & result & "'" & ")"
            'HandleDB2(sql)
            Dim sql As String = "insert into Test_Date(日期,产品条码,产品型号,线别,站别,状态,循环时间) values(" & "'" & dateTime & "'" & "," & "'" & proCount & "'" & "," & "'" & XH & "'" & "," & "'" & NL & "'" & "," & "'" & ScrewTime & "'" & "," & "'" & ScrewQS & "'" & "," & "'" & result & "'" & ")"
            'Dim cnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= Tool\Test_Date.accdb;Persist Security Info=False"
            'Dim cn As OleDbConnection = New OleDbConnection(cnStr)
            'cn.Open()
            'Dim dc As OleDbCommand = New OleDbCommand(sql, cn)
            'Dim i As Integer = dc.ExecuteNonQuery()
            'cn.Close()
            HandleMysql(sql)
        Catch ex As Exception
            MsgBox("SaveDeviation:" & ex.Message.ToString)
        End Try
    End Sub

    Private Sub SaveDeviation1(ByVal dateTime As String, ByVal proCount As String, ByVal XH As String, ByVal NL As String, ByVal ScrewTime As String, ByVal result As String)
        Try
            Dim sql As String = "insert into errorinfo(日期,产品条码,产品型号,线别,站别,报警信息) values(" & "'" & dateTime & "'" & "," & "'" & proCount & "'" & "," & "'" & XH & "'" & "," & "'" & NL & "'" & "," & "'" & ScrewTime & "'" & "," & "'" & result & "'" & ")"
            HandleMysql(sql)
        Catch ex As Exception
            MsgBox("SaveDeviation:" & ex.Message.ToString)
        End Try
    End Sub

    Private Sub ONECheck_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ONECheck_Button.Click
        Test_Date_deleted()
        If DateTimePicker3.Value > DateTimePicker4.Value Then
            MsgBox("查询开始时间大于结束时间！")
        Else
            Dim sql As String = "select * from Test_Date where 日期 >=" & "'" & Format(DateTimePicker3.Value, "yyyy-MM-dd HH:mm:ss") & "'" & "and " & "日期 <=" & "'" & Format(DateTimePicker4.Value, "yyyy-MM-dd HH:mm:ss") & "'"
            Dim sql1 As String = sql & "and " & "状态 = 'NG'"
            Dim ds As DataSet = SearchMysql(sql)
            Dim ds1 As DataSet = SearchMysql(sql1)
            'DataGridView2.AutoGenerateColumns = True
            DataGridView3.DataSource = ds.Tables(0)  '''''''''''''TextBox8.Text = DataGridView3.Rows.Count

            TextBox8.Text = ds.Tables(0).Rows.Count
            TextBox9.Text = ds1.Tables(0).Rows.Count
            Dim LN As Double = 100 * (1 - Val(TextBox9.Text) / Val(TextBox8.Text))
            TextBox10.Text = Format(LN, "0.00") & "%"
        End If
    End Sub

    Private Sub AllCheck_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AllCheck_Button.Click
        Dim sql As String = "select * from Test_Date"
        Dim sql1 As String = "select * from Test_Date where 状态 = 'NG'"
        Dim ds As DataSet = SearchMysql(sql)
        Dim ds1 As DataSet = SearchMysql(sql1)
        DataGridView3.DataSource = ds.Tables(0)

        TextBox8.Text = ds.Tables(0).Rows.Count '''''''''''''TextBox8.Text = DataGridView3.Rows.Count
        TextBox9.Text = ds1.Tables(0).Rows.Count
        Dim LN As Double = 100 * (1 - Val(TextBox9.Text) / Val(TextBox8.Text))
        TextBox10.Text = Format(LN, "0.00") & "%"
    End Sub

    Private Sub Out_Button10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Out_Button10.Click
        ExportExcel(DataGridView3, "生产报表")
    End Sub

    Private Sub Test_Date_deleted()
        Try
            Dim dt As DateTime = DateTime.Now
            Dim dt2 As DateTime = dt.AddYears(-1) '减去一年
            Dim dt3 As DateTime = dt.AddDays(-30) '减去30天

            'Dim cnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= Tool\Test_Date.accdb;Persist Security Info=False"
            Dim sql As String = "delete from  Test_Date where 日期 <" & "'" & Format(dt2, "yyyy-MM-dd HH:mm:ss") & "'"
            HandleMysql(sql)
        Catch ex As Exception
            'Error_report_storage(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), Todaycount.PassCount + 1, Chanpin, ex.Message.ToString, "待分析", "咨询生产厂商", "软件故障")   '''信息写入数据库中
            AppendInfoToTextBox(ex.Message.ToString)
            MsgBox(ex.Message.ToString & vbCrLf & ex.StackTrace.ToString)
        End Try

    End Sub

#End Region

#Region "报表execl导出"""

    Public Function ExportExcel(ByVal dgv As DataGridView, ByVal folder As String) As Boolean
        Try
            'If dgv.Rows.Count > 1 Then
            'If dgv.Rows.Count < 1000 Then
            'Dim myExcel As New Microsoft.Office.Interop.Excel.Application
            ' myExcel.Application.Workbooks.Add(True)
            ' myExcel.Visible = True
            '导出表头
            'Dim i, j, k As Integer
            ''''<span style="white-space:pre">	</span>'利用循环，填写表头
            'For k = 0 To dgv.ColumnCount - 1
            '   myExcel.Cells(1, k + 1) = dgv.Columns(k).HeaderText
            '  myExcel.Cells(1, k + 1).font.bold = True '''''字体为粗体
            ' myExcel.Cells(1, k + 1).font.size = 12 '''''字体为12粗体
            ' Next
            '利用循环嵌套，将datagridview内容放到导出为excel表格
            '这里有两个循环i表示行循环，j为列循环，excel先从行开始循环，excel需要从列开始循环
            'For i = 0 To dgv.Rows.Count - 2
            '    For j = 0 To dgv.ColumnCount - 1
            '        myExcel.Cells(i + 2, j + 1) = dgv(j, i).Value.ToString
            '    Next
            ' Next
            ' myExcel.Range("A:H").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter '''''表格文字居中
            'myExcel.Columns.EntireColumn.AutoFit() '''''列宽自适应

            'Dim openresult As Boolean = Exists(gVisionFailedPath & folder)
            ' If openresult = False Then
            '     Directory.CreateDirectory(gVisionFailedPath & folder)
            'End If
            '
            ' myExcel.ActiveWorkbook.SaveAs(gVisionFailedPath & folder & "/" & Format(DateAndTime.Now, "yyyyMMddHHmmss") & ".xlsx")
            ' myExcel.Quit()
            ' myExcel = Nothing
            'myExcel.ActiveWorkbook.SaveAs(Filename:=openresult & "\DEMO1.xls")
            'myExcel.ActiveWorkbook.SaveAs(Filename:="C:\EXCEL\DEMO1.xls")
            'myExcel.Workbooks.Close()
            ' MsgBox("导出成功")
            'Else
            '   MsgBox("提示：导出数据过大，无法导出！最大只能导出1000条。")
            'End If
            'Else
            'MsgBox("提示：表格中没有数据记录，不能进行导出数据！")
            'End If
            Return True
        Catch ex As Exception
            Return False
            'Error_report_storage(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), ex.Message.ToString, "待分析", "咨询生产厂商", "软件故障")   '''信息写入数据库中
            AppendInfoToTextBox(ex.Message.ToString)
            MsgBox(ex.Message.ToString & vbCrLf & ex.StackTrace.ToString)
        End Try
    End Function

#End Region

#Region "查询付锁报表"""

    Private Sub ScrewtoAccess(ByVal sn As String, ByVal dateTime As String, ByVal proCount As String, ByVal XH As String, ByVal NL As String, ByVal ScrewTime As String, ByVal ScrewQS As String, ByVal result As String)
        Try
            Dim sql As String = "insert into Look_screw(SN,日期,当日数量,产品型号,锁附扭力,时间,站别,结果) values(" & "'" & sn & "'" & "," & "'" & dateTime & "'" & "," & "'" & proCount & "'" & "," & "'" & XH & "'" & "," & "'" & NL & "'" & "," & "'" & ScrewTime & "'" & "," & "'" & ScrewQS & "'" & "," & "'" & result & "'" & ")"
            HandleMysql(sql)
        Catch ex As Exception
            AppendInfoToTextBox("ScrewtoAccess:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
    End Sub

    Private Sub LoadAccess1()
        Try
            Dim sql As String = "select * from Look_screw"
            Dim sql1 As String = "select * from Look_screw where 结果 = 'NG'"
            Dim ds As DataSet = SearchMysql(sql)
            Dim ds1 As DataSet = SearchMysql(sql1)
            DataGridView2.DataSource = ds.Tables(0)

            TextBox13.Text = ds.Tables(0).Rows.Count
            TextBox12.Text = ds1.Tables(0).Rows.Count
            Dim LN As Double = 100 * (1 - Val(TextBox12.Text) / Val(TextBox13.Text))
            TextBox11.Text = Format(LN, "0.00") & "%"
        Catch ex As Exception
            AppendInfoToTextBox("LoadAccess1:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try

    End Sub

    Private Sub Button6_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button6.Click

        If DateTimePicker1.Value > DateTimePicker2.Value Then
            MsgBox("查询开始时间大于结束时间！")
        Else
            Dim sql As String = "select * from Look_screw where 日期 >=" & "'" & Format(DateTimePicker1.Value, "yyyy-MM-dd HH:mm:ss") & "'" & "and " & "日期 <=" & "'" & Format(DateTimePicker2.Value, "yyyy-MM-dd HH:mm:ss") & "'"
            Dim sql1 As String = sql & "and " & "结果 = 'NG'"
            Dim ds As DataSet = SearchMysql(sql)
            Dim ds1 As DataSet = SearchMysql(sql1)
            'DataGridView2.AutoGenerateColumns = True
            DataGridView2.DataSource = ds.Tables(0)

            TextBox13.Text = ds.Tables(0).Rows.Count
            TextBox12.Text = ds1.Tables(0).Rows.Count
            Dim LN As Double = 100 * (1 - Val(TextBox12.Text) / Val(TextBox13.Text))
            TextBox11.Text = Format(LN, "0.00") & "%"
        End If
    End Sub

    Private Sub Button7_Click_1(ByVal sender As Object, ByVal e As EventArgs) Handles Button7.Click
        LoadAccess1()
    End Sub

    Private Sub Button8_Click_1(ByVal sender As Object, ByVal e As EventArgs) Handles Button8.Click
        ExportExcel(DataGridView2, "锁付报表")
    End Sub

    Private Sub Look_screw_deleted()
        Try
            Dim dt As DateTime = DateTime.Now
            Dim dt2 As DateTime = dt.AddYears(-1) '减去一年
            Dim dt3 As DateTime = dt.AddDays(-30) '减去30天
            Dim sql As String = "delete from  Look_screw where 日期 <" & "'" & Format(dt2, "yyyy-MM-dd HH:mm:ss") & "'"
            AppendInfoToTextBox(sql)
            HandleMysql(sql)
        Catch ex As Exception
            AppendInfoToTextBox(ex.Message.ToString)
            ' MsgBox(ex.Message.ToString & vbCrLf & ex.StackTrace.ToString)
        End Try

    End Sub

#End Region

#Region "饼状图良率统计"""

    ''' 饼状图良率统计
    ''' <summary>
    ''' 添加实时曲线的全部类型
    '''
    Public shuzhu(10, 36) As Double

    Public current_time(36) As String

    Protected Sub iniChart()
        Try
            '''''''''''''''''''''''''lianglv外框属性''''''''''''''''''''''''''''''''''''''''''
            lianglv.BackColor = Color.FromName("GradientInactiveCaption") '设置绘图区颜色
            lianglv.BackGradientStyle = GradientStyle.HorizontalCenter '设置绘图区颜色渐变方式\

            '''''''''''''''''''''''''lianglv绘图区属性''''''''''''''''''''''''''''''''''''''''''
            lianglv.ChartAreas.Clear() '清除所有绘图区
            Dim newChartAreas1 As New ChartArea("Default") '新增绘图区
            lianglv.ChartAreas.Add(newChartAreas1)
            lianglv.ChartAreas("Default").BackColor = Color.FromName("GradientInactiveCaption") '设置绘图区颜色
            lianglv.ChartAreas("Default").BackGradientStyle = GradientStyle.HorizontalCenter '设置绘图区颜色渐变方式
            lianglv.ChartAreas("Default").AxisX.IsMarginVisible = True
            ' lianglv.ChartAreas("Default").Area3DStyle.Enable3D = True           '启用3D显示

            '''''''''''''''''''''''''lianglv标题属性''''''''''''''''''''''''''''''''''''''''''
            lianglv.Titles.Clear()
            Dim newTitles1 As New Title("合格率(颗)") '建立标题
            newTitles1.Text = "合格率(颗)"
            newTitles1.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
            'newTitles1.BackColor = Color.Lime       ‘外框颜色
            newTitles1.ForeColor = Color.Lime         '字体颜色
            lianglv.Titles.Add(newTitles1)             '添加lianglv标题

            '''''''''''''''''''''''''XY网格''''''''''''''''''''''''''''''''''''''''''
            lianglv.ChartAreas("Default").AxisX.Interval = 3                                  '//设置X轴坐标的间隔为1
            'lianglv.ChartAreas("Default").AxisX.IntervalOffset = 1                            '//设置X轴坐标的偏移为1
            lianglv.ChartAreas("Default").AxisX.LabelStyle.Interval = 3                      '//设置X轴坐标的值的间隔为1
            lianglv.ChartAreas("Default").AxisX.MajorGrid.LineColor = Color.Wheat              '//设置X轴网格颜色
            lianglv.ChartAreas("Default").AxisX.MajorGrid.LineDashStyle = ChartDashStyle.Dot   '//设置X轴网格类型
            lianglv.ChartAreas("Default").AxisX.Title = "时间"                                 'X轴名称
            lianglv.ChartAreas("Default").AxisX.TitleFont = New System.Drawing.Font("微软雅黑", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
            lianglv.ChartAreas("Default").AxisX.TitleForeColor = Color.Black                   '字体颜色
            lianglv.ChartAreas("Default").AxisX.TextOrientation = TextOrientation.Horizontal   '字体方向

            lianglv.ChartAreas("Default").AxisY.Interval = 10                                  '//设置Y轴坐标的间隔为1
            'lianglv.ChartAreas("Default").AxisY.IntervalOffset = 1                            '//设置Y轴坐标的偏移为1
            lianglv.ChartAreas("Default").AxisY.LabelStyle.Interval = 10                       '//设置Y轴坐标的值的间隔为1
            lianglv.ChartAreas("Default").AxisY.MajorGrid.LineColor = Color.Wheat              '//设置Y轴网格颜色
            lianglv.ChartAreas("Default").AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Dot   '//设置Y轴网格类型
            lianglv.ChartAreas("Default").AxisY.Title = "数量"                                 'Y轴名称
            lianglv.ChartAreas("Default").AxisY.TitleFont = New System.Drawing.Font("微软雅黑", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
            lianglv.ChartAreas("Default").AxisY.TitleForeColor = Color.Black                   '字体颜色
            lianglv.ChartAreas("Default").AxisY.TextOrientation = TextOrientation.Rotated270   '字体方向

            '''''''''''''''''''''''''数据处理''''''''''''''''''''''''''''''''''''''''''
            Dim dt As New DataTable                 '定义一个数据表
            '表增加日期、1#曲线
            dt.Columns.Add("日期")                  '添加日期数据列
            dt.Columns.Add("1#曲线")                  '添加1#曲线数据列

            current_time(0) = "合格"    '行日期数据写入
            current_time(1) = "异常"    '行日期数据写入

            If PassCount.Text = "0" Or ScrewCount.Text = "0" Then
                shuzhu(0, 0) = 100
            Else
                shuzhu(0, 0) = Format(100 * (1 - (Val(SCount.Text) / Val(ScrewCount.Text))), "0.00")
            End If
            shuzhu(0, 1) = Format(100 - shuzhu(0, 0), "0.00")

            Dim dr As DataRow
            For i As Integer = 1 To 2
                '新增行
                dr = dt.NewRow()                    '行寻址
                dr.Item(0) = current_time(i - 1)    '行日期数据写入
                dr.Item(1) = shuzhu(0, i - 1)       '行1#曲线数据写入
                dt.Rows.Add(dr)
            Next
            dr = Nothing

            With Me.lianglv
                .DataSource = dt    'dt作为lianglv的数据源
                .Series.Clear()
                .Legends.Clear()
                .Legends.Add("1#曲线")
                .Series.Add("1#曲线")

            End With

            With Me.lianglv
                .DataSource = dt    'dt作为lianglv的数据源
                .Series.Clear()
                .Legends.Clear()
                .Series.Add("1#曲线")
                .Legends.Add("1#曲线")
                .Series("1#曲线").Legend = "1#曲线"                 '指定Legend所属Series
                .Series("1#曲线").LegendToolTip = "1#曲线图例"
                .Series("1#曲线").IsValueShownAsLabel = True    '标签显示数据值
            End With
            With (lianglv.Series("1#曲线"))
                '指定x、y轴数据列
                .YValueMembers = "1#曲线"
                .XValueMember = "日期"
                .ChartType = 18               '图表类型
                '.ChartType = DataVisualization.Charting.SeriesChartType.Line     '图表类型
            End With
        Catch ex As Exception
            MsgBox(ex.Message.ToString & vbCrLf & ex.StackTrace.ToString)
        End Try
    End Sub

    Protected Sub iniChart2()
        Try
            '''''''''''''''''''''''''lianglv外框属性''''''''''''''''''''''''''''''''''''''''''
            lianglvtai.BackColor = Color.FromName("GradientInactiveCaption") '设置绘图区颜色
            lianglvtai.BackGradientStyle = GradientStyle.HorizontalCenter '设置绘图区颜色渐变方式\

            '''''''''''''''''''''''''lianglvtai绘图区属性''''''''''''''''''''''''''''''''''''''''''
            lianglvtai.ChartAreas.Clear() '清除所有绘图区
            Dim newChartAreas1 As New ChartArea("Default") '新增绘图区
            lianglvtai.ChartAreas.Add(newChartAreas1)
            lianglvtai.ChartAreas("Default").BackColor = Color.FromName("GradientInactiveCaption") '设置绘图区颜色
            lianglvtai.ChartAreas("Default").BackGradientStyle = GradientStyle.HorizontalCenter '设置绘图区颜色渐变方式
            lianglvtai.ChartAreas("Default").AxisX.IsMarginVisible = True
            ' lianglvtai.ChartAreas("Default").Area3DStyle.Enable3D = True           '启用3D显示

            '''''''''''''''''''''''''lianglvtai标题属性''''''''''''''''''''''''''''''''''''''''''
            lianglvtai.Titles.Clear()
            Dim newTitles1 As New Title("合格率(台)") '建立标题
            newTitles1.Text = "合格率(台)"
            newTitles1.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
            'newTitles1.BackColor = Color.Lime       ‘外框颜色
            newTitles1.ForeColor = Color.Lime         '字体颜色
            lianglvtai.Titles.Add(newTitles1)             '添加lianglvtai标题

            '''''''''''''''''''''''''XY网格''''''''''''''''''''''''''''''''''''''''''
            lianglvtai.ChartAreas("Default").AxisX.Interval = 3                                  '//设置X轴坐标的间隔为1
            'lianglvtai.ChartAreas("Default").AxisX.IntervalOffset = 1                            '//设置X轴坐标的偏移为1
            lianglvtai.ChartAreas("Default").AxisX.LabelStyle.Interval = 3                      '//设置X轴坐标的值的间隔为1
            lianglvtai.ChartAreas("Default").AxisX.MajorGrid.LineColor = Color.Wheat              '//设置X轴网格颜色
            lianglvtai.ChartAreas("Default").AxisX.MajorGrid.LineDashStyle = ChartDashStyle.Dot   '//设置X轴网格类型
            lianglvtai.ChartAreas("Default").AxisX.Title = "时间"                                 'X轴名称
            lianglvtai.ChartAreas("Default").AxisX.TitleFont = New System.Drawing.Font("微软雅黑", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
            lianglvtai.ChartAreas("Default").AxisX.TitleForeColor = Color.Black                   '字体颜色
            lianglvtai.ChartAreas("Default").AxisX.TextOrientation = TextOrientation.Horizontal   '字体方向

            lianglvtai.ChartAreas("Default").AxisY.Interval = 10                                  '//设置Y轴坐标的间隔为1
            'lianglvtai.ChartAreas("Default").AxisY.IntervalOffset = 1                            '//设置Y轴坐标的偏移为1
            lianglvtai.ChartAreas("Default").AxisY.LabelStyle.Interval = 10                       '//设置Y轴坐标的值的间隔为1
            lianglvtai.ChartAreas("Default").AxisY.MajorGrid.LineColor = Color.Wheat              '//设置Y轴网格颜色
            lianglvtai.ChartAreas("Default").AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Dot   '//设置Y轴网格类型
            lianglvtai.ChartAreas("Default").AxisY.Title = "数量"                                 'Y轴名称
            lianglvtai.ChartAreas("Default").AxisY.TitleFont = New System.Drawing.Font("微软雅黑", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
            lianglvtai.ChartAreas("Default").AxisY.TitleForeColor = Color.Black                   '字体颜色
            lianglvtai.ChartAreas("Default").AxisY.TextOrientation = TextOrientation.Rotated270   '字体方向

            '''''''''''''''''''''''''数据处理''''''''''''''''''''''''''''''''''''''''''
            Dim dt As New DataTable                 '定义一个数据表
            '表增加日期、1#曲线
            dt.Columns.Add("日期")                  '添加日期数据列
            dt.Columns.Add("1#曲线")                  '添加1#曲线数据列

            current_time(0) = "合格"    '行日期数据写入
            current_time(1) = "异常"    '行日期数据写入

            If PassCount.Text = "0" Then
                shuzhu(0, 0) = "100.00 "
            Else
                shuzhu(0, 0) = Format(100 * (1 - Val(TextBox_PCSFailed.Text) / Val(PassCount.Text)), "0.00")
            End If
            shuzhu(0, 1) = Format(100 - shuzhu(0, 0), "0.00")

            Dim dr As DataRow
            For i As Integer = 1 To 2
                '新增行
                dr = dt.NewRow()                    '行寻址
                dr.Item(0) = current_time(i - 1)    '行日期数据写入
                dr.Item(1) = shuzhu(0, i - 1)       '行1#曲线数据写入
                dt.Rows.Add(dr)
            Next
            dr = Nothing

            With Me.lianglvtai
                .DataSource = dt    'dt作为lianglvtai的数据源
                .Series.Clear()
                .Legends.Clear()
                .Legends.Add("1#曲线")
                .Series.Add("1#曲线")
            End With

            With Me.lianglvtai
                .DataSource = dt    'dt作为lianglvtai的数据源
                .Series.Clear()
                .Legends.Clear()
                .Series.Add("1#曲线")
                .Legends.Add("1#曲线")
                .Series("1#曲线").Legend = "1#曲线"                 '指定Legend所属Series
                .Series("1#曲线").LegendToolTip = "1#曲线图例"
                .Series("1#曲线").IsValueShownAsLabel = True    '标签显示数据值
            End With
            With (lianglvtai.Series("1#曲线"))
                '指定x、y轴数据列
                .YValueMembers = "1#曲线"
                .XValueMember = "日期"
                .ChartType = 18               '图表类型
                '.ChartType = DataVisualization.Charting.SeriesChartType.Line     '图表类型
            End With
        Catch ex As Exception
            MsgBox(ex.Message.ToString & vbCrLf & ex.StackTrace.ToString)
        End Try
    End Sub

#End Region

    Private Sub Timerclear_Tick(sender As Object, e As EventArgs) Handles Timerclear.Tick
        Try
            If newset(6) = True And (Now.Hour = Clear_Time Or Now.Hour = Clear_Time + 12) And Now.Minute = 0 Then
                Todaycount.ScanSN = 0
                Todaycount.NGCount = 0
                Todaycount.PassCount = 0
                Todaycount.SCount = 0
                Todaycount.ScrewCount = 0
                Todaycount.ScrewFailed1 = 0
                Todaycount.ScrewFailed2 = 0
                Todaycount.ScrewFailed3 = 0
                Todaycount.ScrewFailed4 = 0
                Todaycount.ScrewFailed5 = 0
                Todaycount.ScrewFailed6 = 0
                Todaycount.ScrewFailed7 = 0
                Todaycount.ScrewFailed8 = 0
                Todaycount.ScrewFailed9 = 0
                Todaycount.ScrewFailed10 = 0
                Todaycount.ScrewFailed11 = 0
                Todaycount.ScrewFailed12 = 0
                Todaycount.ScrewFailed13 = 0
                Todaycount.ScrewFailed14 = 0
                Todaycount.ScrewFailed15 = 0
                Todaycount.ScrewFailed16 = 0
                Todaycount.ScrewFailed17 = 0
                Todaycount.ScrewFailed18 = 0
                Todaycount.ScrewFailed19 = 0
                Todaycount.ScrewFailed20 = 0
                Todaycount.ScrewFailed21 = 0
                Todaycount.ScrewFailed22 = 0
                Todaycount.ScrewFailed23 = 0
                Todaycount.ScrewFailed24 = 0
                Todaycount.ScrewFailed25 = 0
                Todaycount.ScrewFailed26 = 0
                Todaycount.ScrewFailed27 = 0
                Todaycount.ScrewFailed28 = 0
                Todaycount.ScrewFailed29 = 0
                Todaycount.ScrewFailed30 = 0
                Todaycount.ScrewFailed31 = 0
                Todaycount.ScrewFailed32 = 0
                Todaycount.ScrewFailed33 = 0
                Todaycount.ScrewFailed34 = 0
                Todaycount.ScrewFailed35 = 0
                Todaycount1.SNCount = 0
                Todaycount1.SN_Check = 0

                TextBox1.Text = Todaycount.ScanSN.ToString

                PassCount.Text = Todaycount.PassCount.ToString
                NGCount.Text = Todaycount.NGCount.ToString
                SCount.Text = Todaycount.SCount.ToString
                ScrewCount.Text = Todaycount.ScrewCount.ToString
                ScrewFailed1.Text = Todaycount.ScrewFailed1.ToString
                ScrewFailed2.Text = Todaycount.ScrewFailed2.ToString
                ScrewFailed3.Text = Todaycount.ScrewFailed3.ToString
                ScrewFailed4.Text = Todaycount.ScrewFailed4.ToString
                ScrewFailed5.Text = Todaycount.ScrewFailed5.ToString
                ScrewFailed6.Text = Todaycount.ScrewFailed6.ToString
                ScrewFailed7.Text = Todaycount.ScrewFailed7.ToString
                ScrewFailed8.Text = Todaycount.ScrewFailed8.ToString
                ScrewFailed9.Text = Todaycount.ScrewFailed9.ToString
                ScrewFailed10.Text = Todaycount.ScrewFailed10.ToString
                ScrewFailed11.Text = Todaycount.ScrewFailed11.ToString
                ScrewFailed12.Text = Todaycount.ScrewFailed12.ToString
                ScrewFailed13.Text = Todaycount.ScrewFailed13.ToString
                ScrewFailed14.Text = Todaycount.ScrewFailed14.ToString
                ScrewFailed15.Text = Todaycount.ScrewFailed15.ToString
                ScrewFailed16.Text = Todaycount.ScrewFailed16.ToString
                ScrewFailed17.Text = Todaycount.ScrewFailed17.ToString
                ScrewFailed18.Text = Todaycount.ScrewFailed18.ToString
                ScrewFailed19.Text = Todaycount.ScrewFailed19.ToString
                ScrewFailed20.Text = Todaycount.ScrewFailed20.ToString
                ScrewFailed21.Text = Todaycount.ScrewFailed21.ToString
                ScrewFailed22.Text = Todaycount.ScrewFailed22.ToString
                ScrewFailed23.Text = Todaycount.ScrewFailed23.ToString
                ScrewFailed24.Text = Todaycount.ScrewFailed24.ToString
                ScrewFailed25.Text = Todaycount.ScrewFailed25.ToString
                ScrewFailed26.Text = Todaycount.ScrewFailed26.ToString
                ScrewFailed27.Text = Todaycount.ScrewFailed27.ToString
                ScrewFailed28.Text = Todaycount.ScrewFailed28.ToString
                ScrewFailed29.Text = Todaycount.ScrewFailed29.ToString
                ScrewFailed30.Text = Todaycount.ScrewFailed30.ToString
                TxtBlowNum.Text = Todaycount.ScrewFailed35.ToString
                Todaycount.SuctionCount = 0
                Todaycount.CycleTime = 0
                Todaycount.PCSFailedCount = 0
                Todaycount.SuctionCount = 0
                SuctionCount.Text = Todaycount.SuctionCount
                TextBox_CT.Text = 0
                TextBox_PCSFailed.Text = 0
                Suction = 0
                IsFirstSend = 1

            End If
            If Exists(gProDataPath & "\count.txt") Then
                FileOpen(file_num_count, gProDataPath & "\count.txt", OpenMode.Random, , , RecordLength:=Len(Todaycount))
                FilePut(file_num_count, Todaycount)
                FileClose(file_num_count)
            End If

            If Exists(gProDataPath & "\count1.txt") Then
                FileOpen(file_num_count1, gProDataPath & "\count1.txt", OpenMode.Random, , , RecordLength:=Len(Todaycount))
                FilePut(file_num_count1, Todaycount1)
                FileClose(file_num_count1)
            End If
        Catch ex As Exception
            Timerclear.Enabled = False
            MsgBox("time:" & ex.Message.ToString & ex.StackTrace.ToString())
        End Try
    End Sub

    Private Sub TimerFlag_Tick(sender As Object, e As EventArgs) Handles TimerFlag.Tick
        TimerFlag.Enabled = False
        '刷新队列
        Try
            If showSNQueueFlag = True Then
                showSNQueueFlag = False
                ShowCurrentSNListQueue() '切换到显示队列页面时卡死问题
            End If
        Catch ex As Exception
        End Try

        Try
            If Can_Barcode = True Then
                Button_CanBarcode.Text = "读码中"
                Button_CanBarcode.BackColor = Color.Lime
            Else
                Button_CanBarcode.Text = "禁止读码"
                Button_CanBarcode.BackColor = Color.WhiteSmoke
            End If
        Catch ex As Exception
        End Try

        Try
            iniChart()
            iniChart2()
            If Flag = "S" Then
                Flag = "0"
                If IsScrewFail = True And Suction = "" Then
                    Todaycount.PCSFailedCount += 1
                    TextBox_PCSFailed.Text = Todaycount.PCSFailedCount.ToString         '异常台数
                    IsScrewFail = False
                End If

                If Suction = "" Then
                    Todaycount.SCount += 1
                    ' FilePut(file_num_count, Todaycount)
                    SCount.Text = Todaycount.SCount.ToString          '异常颗数
                End If

                '各个点位失败次数
                If Screw = "1" And Suction = "" Then
                    Todaycount.ScrewFailed1 += 1
                    ScrewFailed1.Text = Todaycount.ScrewFailed1.ToString
                End If
                If Screw = "2" And Suction = "" Then
                    Todaycount.ScrewFailed2 += 1
                    ScrewFailed2.Text = Todaycount.ScrewFailed2.ToString
                End If
                If Screw = "3" And Suction = "" Then
                    Todaycount.ScrewFailed3 += 1
                    ScrewFailed3.Text = Todaycount.ScrewFailed3.ToString
                End If
                If Screw = "4" And Suction = "" Then
                    Todaycount.ScrewFailed4 += 1
                    ScrewFailed4.Text = Todaycount.ScrewFailed4.ToString
                End If
                If Screw = "5" And Suction = "" Then
                    Todaycount.ScrewFailed5 += 1
                    ScrewFailed5.Text = Todaycount.ScrewFailed5.ToString
                End If
                If Screw = "6" And Suction = "" Then
                    Todaycount.ScrewFailed6 += 1
                    ScrewFailed6.Text = Todaycount.ScrewFailed6.ToString
                End If
                If Screw = "7" And Suction = "" Then
                    Todaycount.ScrewFailed7 += 1
                    ScrewFailed7.Text = Todaycount.ScrewFailed7.ToString
                End If
                If Screw = "8" And Suction = "" Then
                    Todaycount.ScrewFailed8 += 1
                    ScrewFailed8.Text = Todaycount.ScrewFailed8.ToString
                End If
                If Screw = "9" And Suction = "" Then
                    Todaycount.ScrewFailed9 += 1
                    ScrewFailed9.Text = Todaycount.ScrewFailed9.ToString
                End If
                If Screw = "10" And Suction = "" Then
                    Todaycount.ScrewFailed10 += 1
                    ScrewFailed10.Text = Todaycount.ScrewFailed10.ToString
                End If
                If Screw = "11" And Suction = "" Then
                    Todaycount.ScrewFailed11 += 1
                    ScrewFailed11.Text = Todaycount.ScrewFailed11.ToString
                End If
                If Screw = "12" And Suction = "" Then
                    Todaycount.ScrewFailed12 += 1
                    ScrewFailed12.Text = Todaycount.ScrewFailed12.ToString
                End If
                If Screw = "13" And Suction = "" Then
                    Todaycount.ScrewFailed13 += 1
                    ScrewFailed13.Text = Todaycount.ScrewFailed13.ToString
                End If
                If Screw = "14" And Suction = "" Then
                    Todaycount.ScrewFailed14 += 1
                    ScrewFailed14.Text = Todaycount.ScrewFailed14.ToString
                End If
                If Screw = "15" And Suction = "" Then
                    Todaycount.ScrewFailed15 += 1
                    ScrewFailed15.Text = Todaycount.ScrewFailed15.ToString
                End If
                If Screw = "16" And Suction = "" Then
                    Todaycount.ScrewFailed16 += 1
                    ScrewFailed16.Text = Todaycount.ScrewFailed16.ToString
                End If
                If Screw = "17" And Suction = "" Then
                    Todaycount.ScrewFailed17 += 1
                    ScrewFailed17.Text = Todaycount.ScrewFailed17.ToString

                End If
                If Screw = "18" And Suction = "" Then
                    Todaycount.ScrewFailed18 += 1
                    ScrewFailed18.Text = Todaycount.ScrewFailed18.ToString

                End If
                If Screw = "19" And Suction = "" Then
                    Todaycount.ScrewFailed19 += 1
                    ScrewFailed19.Text = Todaycount.ScrewFailed19.ToString

                End If
                If Screw = "20" And Suction = "" Then
                    Todaycount.ScrewFailed20 += 1
                    ScrewFailed20.Text = Todaycount.ScrewFailed20.ToString

                End If
                If Screw = "21" And Suction = "" Then
                    Todaycount.ScrewFailed21 += 1
                    ScrewFailed21.Text = Todaycount.ScrewFailed21.ToString

                End If
                If Screw = "22" And Suction = "" Then
                    Todaycount.ScrewFailed22 += 1
                    ScrewFailed22.Text = Todaycount.ScrewFailed22.ToString

                End If
                If Screw = "23" And Suction = "" Then
                    Todaycount.ScrewFailed23 += 1
                    ScrewFailed23.Text = Todaycount.ScrewFailed23.ToString

                End If

                If Screw = "24" And Suction = "" Then
                    Todaycount.ScrewFailed24 += 1
                    ScrewFailed24.Text = Todaycount.ScrewFailed24.ToString

                End If
                If Screw = "25" And Suction = "" Then
                    Todaycount.ScrewFailed25 += 1
                    ScrewFailed25.Text = Todaycount.ScrewFailed25.ToString

                End If
                If Screw = "26" And Suction = "" Then
                    Todaycount.ScrewFailed26 += 1
                    ScrewFailed26.Text = Todaycount.ScrewFailed26.ToString

                End If
                If Screw = "27" And Suction = "" Then
                    Todaycount.ScrewFailed27 += 1
                    ScrewFailed27.Text = Todaycount.ScrewFailed27.ToString

                End If
                If Screw = "28" And Suction = "" Then
                    Todaycount.ScrewFailed28 += 1
                    ScrewFailed28.Text = Todaycount.ScrewFailed28.ToString

                End If
                If Screw = "29" And Suction = "" Then
                    Todaycount.ScrewFailed29 += 1
                    ScrewFailed29.Text = Todaycount.ScrewFailed29.ToString

                End If
                If Screw = "30" And Suction = "" Then
                    Todaycount.ScrewFailed30 += 1
                    ScrewFailed30.Text = Todaycount.ScrewFailed30.ToString

                End If

                If Suction = "u" Then
                    Todaycount.SuctionCount += 1
                    SuctionCount.Text = Todaycount.SuctionCount.ToString    '吸螺丝真空异常
                End If
                If Suction = "N" Then
                    Todaycount1.SNCount += 1

                End If
            End If
            iniChart()
            iniChart2()
            'If Flag = "V" Then
            '    Flag = "0"
            '    Todaycount.NGCount += 1
            '    NGCount.Text = Todaycount.NGCount.ToString
            'End If
            '按台计算良率
            If PassCount.Text = "0" Then
                TextBox_Yield.Text = "100.00 %"
            Else
                Dim OKRate As Double = 100 * (1 - Val(TextBox_PCSFailed.Text) / Val(PassCount.Text))
                TextBox_Yield.Text = Format(OKRate, "0.00") & " %"
            End If
            '按颗计算良率
            If ScrewCount.Text = "0" Then
                TextBox7.Text = "100.00 %"
            Else
                Dim ng As Double = 100 * (1 - (Val(SCount.Text) / Val(ScrewCount.Text)))
                TextBox7.Text = Format(ng, "0.00") & " %"
            End If

            If Upload_enable = True Then
                If Flag_YUYING = "OK" Then
                    Flag_YUYING = "NG"
                    'SendSN(Mes_msg)
                End If
            End If
        Catch ex As Exception
            MsgBox("TimerFlag_Tick:" & ex.Message.ToString & ex.StackTrace.ToString())
            'Error_report_storage(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), ex.Message.ToString, "待分析", "咨询生产厂商", "软件故障")   '''信息写入数据库中
        End Try
        TimerFlag.Enabled = True
    End Sub

    Private Sub FrmMain_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
        For Each pro As Process In Process.GetProcesses()
            If pro.ProcessName = "Upload" Or pro.ProcessName = "数据上传" Or pro.ProcessName = "upload" Then
                pro.Kill()
            End If
        Next
        Application.Exit()
        Process.GetCurrentProcess().Kill()
    End Sub

    Private Sub 生产向导ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 生产向导ToolStripMenuItem.Click
        FrmAddProd2.Show()
    End Sub

    Private Sub Timer_Log_Tick(sender As Object, e As EventArgs) Handles Timer_Log.Tick
        Run_time = Date.Now.Hour
        OpenRT_Time = Run_time - Open_time
        If OpenRT_Time > 12 Then
            InitLog()
            Timer_Log.Enabled = False
        End If
    End Sub

    Private Sub Timer_ClearRichTextBoxlog_Tick(sender As Object, e As EventArgs) Handles Timer_ClearRichTextBoxlog.Tick
        RichTextBox_log.Text = ""
    End Sub

    Private Sub TimerLckProd_Tick(sender As Object, e As EventArgs) Handles TimerLckProd.Tick
        TimerLckProd.Enabled = False
        Try
            If SoveProdLuck = True Then
                SaveDeviation(Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), SN_TextBox.Text, Chanpin, machineInfo.Line, machineInfo.Device_id, OPC_Machine_ProductionLog.Result, TextBox_CT.Text)
                SoveProdLuck = False
            End If
            If SoveProdCP = True Then
                SoveProdCP = False
                Dim i As Integer
                i = Screw
                ScrewtoAccess(SN_TextBox.Text, Format(DateAndTime.Now, "yyyy-MM-dd HH:mm:ss"), CurScrewPara.PointCount & "—" & Screw, Chanpin, Lucktorque(i) & "N.M", Luckttime(i) & "s", machineInfo.Device_id, curPcsDetails.Status)
            End If
        Catch ex As Exception

        End Try
        TimerLckProd.Enabled = True

    End Sub

    Private Sub Button_PLC_Click(sender As Object, e As EventArgs) Handles Button_PLC.Click
        If Button_PLC.Text = "PLC联机" Then
        ElseIf Button_PLC.Text = "PLC断开" Then
            Init_plc("192.168.1.55", "1026")
        End If
    End Sub

    ''' 锁附信息发送至从机
    ''' </summary>
    ''' <param name="station"></param>
    ''' <param name="cChanpin"></param>
    ''' <param name="cSN"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function SendSN(ByVal cSN As String) As Boolean

        Dim re As Boolean = False
        Dim result As String = ""
        Dim SendDate As String = ""
        Dim station As String = ""
        Try
            SendDate = cSN & ";" & Chanpin & ";,!"
            Globalfunc.SendDataNORePly(SendDate, LineIP_Date(2), LineIP_Date(3), "UTF8")

            AppendInfoToTextBox("向后一台发送SN数据:" & SendDate)
            re = True
            Return re
        Catch ex As Exception
            AppendInfoToTextBox("联机发送数据异常" + ex.Message)
            re = False
            Return re
        End Try
    End Function

    Private Sub Button_LJ_Click(sender As Object, e As EventArgs) Handles Button_LJ.Click
        '网口2
        If Upload_enable = True Then
            InitTcpSever2()
        Else
            AppendInfoToTextBox("联机功能未打开")
            Button_LJ.Text = "关闭"
            Button_LJ.BackColor = Color.GreenYellow
        End If
    End Sub

    Protected Sub AppendInfoToTextBox(ByVal s As String)           '保存生产数据
        Try
            If (RichTextBox_log.InvokeRequired) Then
                Dim cb As AddRecvToText = New AddRecvToText(AddressOf AppendInfoToTextBox)
                Invoke(cb, s)
            Else
                Dim LogPath As String = CD_Dir & "上位机资料\log\" & Format(Date.Now.Date, "yyyyMMdd") & "\"
                RichTextBox_log.AppendText(s + vbCrLf)
                Dim openresult As Boolean = Exists(LogPath & "\" & "System_Result_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt")
                Dim fileNum As Integer
                fileNum = FreeFile()
                If openresult = False Then
                    Directory.CreateDirectory(LogPath)
                    FileOpen(fileNum, LogPath & "\" & "System_Result_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt", OpenMode.Append)
                    FileClose(fileNum)
                End If
                '文件名
                Dim strSaveFilename As String
                strSaveFilename = LogPath & "\" & "System_Result_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt"
                '打开文件
                FileOpen(fileNum, strSaveFilename, OpenMode.Append)
                '存储文件title
                Print(fileNum, "System_Result_" & Format(Date.Now, "yyyyMMdd HH:mm:ss.ff") & vbTab)
                '存储到文件中
                Print(fileNum, s & vbCrLf)
                '关闭文件
                FileClose(fileNum)
            End If
        Catch ex As Exception
            MsgBox("AppendInfoToTextBox:" & ex.Message.ToString)
        End Try
    End Sub

#Region "三菱plc通讯"""

    Dim melsecMc = New MelsecMcNet            '("192.168.1.55", "1026")

    Protected Sub Sanlin_PLC_Communications_link()
        '连接对象
        Dim connect As OperateResult = melsecMc.ConnectServer()
        If connect.IsSuccess Then
            AppendInfoToTextBox("三菱PLC连接成功,端口1026")
        Else
            AppendInfoToTextBox("三菱PLC连接失败,端口1026")
        End If
    End Sub

    Protected Sub Close_connectPLC()               ''''断开连接
        melsecMc.ConnectClose()
    End Sub

    ''' <summary>
    ''' 写16位数据
    ''' </summary>
    ''' <param name="WriteAdd"></param>
    ''' <param name="WriteDate"></param>
    Private Sub WriteDeviceRandom_Date16(ByVal WriteAdd As String, ByVal WriteDate() As Short)
        Try
            'melsecMc = New MelsecMcNet(WriteId, WriteCnt)
            'Sanlin_PLC_Communications_link()
            'waitstandby(100)

            writeResultRender(melsecMc.Write(WriteAdd, WriteDate), WriteAdd)
            'waitstandby(200)
            'Close_connectPLC()               ''''断开连接
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    '写入32位数据

    Private Sub WriteDeviceRandom_Date32(ByVal WriteAdd As String, ByVal WriteDate() As Integer)
        Try
            'melsecMc = New MelsecMcNet(WriteId, WriteCnt)
            'Sanlin_PLC_Communications_link()
            'waitstandby(100)

            writeResultRender(melsecMc.Write(WriteAdd, WriteDate), WriteAdd)
            'waitstandby(200)
            'Close_connectPLC()               ''''断开连接
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub writeResultRender(ByVal result As OperateResult, ByVal address As String)

        Dim isSuccess As Boolean = result.IsSuccess
        If isSuccess Then
            'AppendInfoToTextBox(("[HH:mm:ss] ") + "[" + address + "] 写入成功")
        Else
            MessageBox.Show(DateTime.Now.ToString("[HH:mm:ss] ") & "[" & address & "] 写入失败" & Environment.NewLine & "原因：" & result.ToMessageShowString())
        End If
    End Sub

    ''   向三菱PLC读取16位数据
    ''例子： ReadDeviceRandom_Date16("D933","1")
    ' Public Function ReadDeviceRandom_Date16(ByVal ReadId As String, ByVal ReadCnt As String, ByVal ReadAdd As String, ByVal ReadLong As Integer)
    Public Function ReadDeviceRandom_Date16(ByVal ReadAdd As String, ByVal ReadLong As Integer)
        Dim ReturmData() As Short
        Try
            'melsecMc = New MelsecMcNet(ReadId, ReadCnt)
            'Sanlin_PLC_Communications_link()
            'waitstandby(100)
            ReturmData = ReadMore16(ReadAdd, ReadLong)

            'waitstandby(200)
            'Close_connectPLC()               ''''断开连接

            Return ReturmData
        Catch ex As Exception
            Return False
            MessageBox.Show(ex.Message)
        End Try
    End Function

    Public Function ReadMore16(ByVal ReadAdd As String, ByVal ReadLong As Integer)
        Try
            Dim data As OperateResult(Of Short()) = melsecMc.ReadInt16(ReadAdd, ReadLong)
            Dim isSuccess As Boolean = data.IsSuccess
            If (isSuccess) Then

                'AppendInfoToTextBox(("[HH:mm:ss] ") + "[" + ReadAdd + "] 读取成功")
                ' returmData = data.Content
            Else

                MessageBox.Show("读取失败：" + data.ToMessageShowString())
            End If

            Return data.Content
        Catch ex As Exception

            MessageBox.Show("读取失败：" + ex.Message)
        End Try
    End Function

    ''   向三菱PLC读取32位数据
    ''例子： ReadDeviceRandom_Date32("D933","1")
    Public Function ReadDeviceRandom_Date32(ByVal ReadAdd As String, ByVal ReadLong As Integer)
        Dim returmData() As Integer
        Try
            'melsecMc = New MelsecMcNet(ReadId, ReadCnt)
            'Sanlin_PLC_Communications_link()
            'waitstandby(100)

            returmData = ReadMore32(ReadAdd, ReadLong)

            'waitstandby(200)
            'Close_connectPLC()               ''''断开连接
            Return returmData
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Function

    '向三菱PLC读取32位数据
    Public Function ReadMore32(ByVal ReadAdd As String, ByVal ReadLong As Integer)
        Try

            Dim data As OperateResult(Of Integer()) = melsecMc.ReadInt32(ReadAdd, ReadLong)
            Dim isSuccess As Boolean = data.IsSuccess
            If (isSuccess) Then

                'AppendInfoToTextBox(("[HH:mm:ss] ") + "[" + ReadAdd + "] 读取成功")
                'returmData = data.Content
            Else

                MessageBox.Show("读取失败：" + data.ToMessageShowString())

            End If
            Return data.Content
        Catch ex As Exception
            Return False
            MessageBox.Show("读取失败：" + ex.Message)
        End Try
    End Function

    Public Function Init_plc(ByVal ReadId As String, ByVal ReadCnt As String)
        Try
            melsecMc = New MelsecMcNet(ReadId, ReadCnt)
            Sanlin_PLC_Communications_link()
            waitstandby(100)

            Button_PLC.Text = "PLC联机"
            Button_PLC.BackColor = Color.Lime

            Return True
        Catch ex As Exception
            Return False
            MessageBox.Show("连接PLC失败：" + ex.Message)
        End Try
    End Function

#End Region

    Private Sub MES数据设置ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MES数据设置ToolStripMenuItem.Click
        FrmMachine.ShowDialog()
    End Sub

    Public Sub OpenLCFCITOTProcess()

        Try
            If newset(0) Then
                'Dim LIST As ArrayList = New ArrayList
                For Each pro As Process In Process.GetProcesses()
                    If pro.ProcessName = "ITOTAgent_OPCUA" Or pro.ProcessName.Contains("ITOTAgent_OPCUA") Or pro.ProcessName.Contains("ITOTAgent") Then
                        Return
                    End If
                    'LIST.Add(pro.ProcessName)
                Next
                AddInfoToMES("重新开启MES程序......")
                If String.IsNullOrEmpty(My.Settings.OPCUAPath) Then
                    AddInfoToMES("重新开启ITOT程序失败：无法找到OPCUA的路径！")
                    Return
                End If
                If Not File.Exists(My.Settings.OPCUAPath) Then
                    AddInfoToMES("重新开启ITOT程序失败：无法找到OPCUA的路径！")
                    Return
                End If
                Dim a As Integer = Shell(My.Settings.OPCUAPath, vbNormalFocus)
                If a = 0 Then
                    AddInfoToMES("IOIT程序打开失败(建议手动打开):" & My.Settings.OPCUAPath)
                End If
            End If
        Catch ex As Exception
            MsgBox("OpenUploadProcess:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try

    End Sub

    ''' <summary>
    ''' 打开数据上传程序
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub OpenUploadProcess()

        Try
            If newset(7) Then
                For Each pro As Process In Process.GetProcesses()
                    If pro.ProcessName = "Upload" Or pro.ProcessName = "数据上传" Or pro.ProcessName = "upload" Then
                        Return
                    End If
                Next
                If Not File.Exists(UploadPath & "\Upload.exe") Then
                    AddInfoToMES("重新开启数据上传程序失败：无法找到数据上传程序的路径！")
                    Return
                End If
                Dim a As Integer = Shell(UploadPath & "\Upload.exe", vbNormalFocus)
                If a = 0 Then
                    AddInfoToMES("数据上传程序打开失败(建议手动打开):" & UploadPath & "\Upload.exe")
                End If
            End If
        Catch ex As Exception
            MsgBox("OpenUploadProcess:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try

    End Sub

    ''' <summary>
    ''' 关闭数据上传程序
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub CloseUploadProcess()
        Try
            Dim winHwnd As IntPtr = FindWindow(vbNullString, "数据上传")
            Dim RetVal As IntPtr
            If winHwnd <> 0 Then
                RetVal = PostMessage(winHwnd, WM_CLOSE, 0&, 0&)
            End If
        Catch ex As Exception
            MsgBox("CloseUploadProcess:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try

    End Sub

    Private Sub 多台联机设置ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 多台联机设置ToolStripMenuItem.Click
        FormIPonline.Show()
    End Sub

    Private Sub 设备保养ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 设备保养ToolStripMenuItem.Click
        If MessageBox.Show("非Stop状态,是否确定要进行此操作？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
            EQ_Status = Equipment_Status._MAINTANCE
            FrmMaintenance.ShowDialog()
            EQ_Status = Equipment_Status._STARTUP
        End If
    End Sub

    Private Sub 设备查看ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 设备查看ToolStripMenuItem.Click
        FrmChech.ShowDialog()
    End Sub

#Region "联宝MES数据上传通讯"

    Private Function MES_BaseDataRequestUpload(ByVal SN As String, ByVal mes1 As String) As String
        Dim result As String = ""
        Dim SendData As String = ""
        Dim MESheader(10, 1) As String
        Dim time As String = Format(DateTime.Now, "yyyyMMddHHmmss")
        Dim skipStr As String = "Prr8tDWJ+Zzzb4UKQ4LmQw==" & machineInfo.UserName & time
        Dim skip As Byte() = Encoding.ASCII.GetBytes(skipStr)
        Dim skipBase64 As String = Convert.ToBase64String(skip)
        MESheader(0, 0) = "X-App"
        MESheader(0, 1) = "nbpec"

        MESheader(1, 0) = "X-Request-Id"
        MESheader(1, 1) = "32e54911-d337-32d2-9a19-21f3a9f22a13" '32e54911-d337-32d2-9a19-21f3a9f22a13

        MESheader(2, 0) = "X-Auth-Meta"
        MESheader(2, 1) = machineInfo.Token

        MESheader(3, 0) = "X-Env"
        MESheader(3, 1) = machineInfo.XEnv

        MESheader(4, 0) = "X-Service"
        MESheader(4, 1) = "datasync"

        MESheader(5, 0) = "X-Skip-Verify"

        MESheader(5, 1) = machineInfo.UserName

        MESheader(6, 0) = "X-Version"
        MESheader(6, 1) = "v1"

        MESheader(7, 0) = "X-Method"
        MESheader(7, 1) = "ORACLEPASS_STATION"

        MESheader(8, 0) = "X-FN"
        MESheader(8, 1) = "AutoPassAPI-ORACLEPASS_STATION"

        MESheader(9, 0) = "X-Date"
        MESheader(9, 1) = time

        MESheader(10, 0) = "X-Rule"
        MESheader(10, 1) = "None"

        'X-Rule

        Try
            SendData = mes1
            AppendInfoToTextBox("发送上传信息到MES：" & SendData)
            '
            If testMode = True Then
                result = TextBox_BaseInfo.Text
                AppendInfoToTextBox("测试模式MES Base数据：" & SendData)
            Else

                If newset(0) = False Then '’
                    result = ""
                Else
                    result = MakeRequest3(machineInfo.MES_UploadAddress, "", 10000, MESheader, SendData)
                    AppendInfoToTextBox("数据上传结果:" & result)
                    Dim returndata As MesReturnData = JsonHelper.DeserializeJson(Of MesReturnData)(result)
                End If
            End If
        Catch ex As Exception
            AppendInfoToTextBox(ex.Message.ToString & ex.StackTrace.ToString)
        End Try
        Return result
    End Function

    Private Function MES_BaseDataRequestUpload(ByVal SN As String, ByVal mes1 As BODY) As String
        Dim result As String = ""
        Dim SendData As String = ""
        Dim MESheader(10, 1) As String
        Dim time As String = Format(DateTime.Now, "yyyyMMddHHmmss")
        Dim skipStr As String = "Prr8tDWJ+Zzzb4UKQ4LmQw==" & machineInfo.UserName & time
        Dim skip As Byte() = Encoding.ASCII.GetBytes(skipStr)
        Dim skipBase64 As String = Convert.ToBase64String(skip)
        MESheader(0, 0) = "X-App"
        MESheader(0, 1) = "nbpec"

        MESheader(1, 0) = "X-Request-Id"
        MESheader(1, 1) = "32e54911-d337-32d2-9a19-21f3a9f22a13" '32e54911-d337-32d2-9a19-21f3a9f22a13

        MESheader(2, 0) = "X-Auth-Meta"
        MESheader(2, 1) = machineInfo.Token

        MESheader(3, 0) = "X-Env"
        MESheader(3, 1) = machineInfo.XEnv

        MESheader(4, 0) = "X-Service"
        MESheader(4, 1) = "datasync"

        MESheader(5, 0) = "X-Skip-Verify"

        MESheader(5, 1) = machineInfo.UserName

        MESheader(6, 0) = "X-Version"
        MESheader(6, 1) = "v1"

        MESheader(7, 0) = "X-Method"
        MESheader(7, 1) = "ORACLEPASS_STATION"

        MESheader(8, 0) = "X-FN"
        MESheader(8, 1) = "AutoPassAPI-ORACLEPASS_STATION"

        MESheader(9, 0) = "X-Date"
        MESheader(9, 1) = time

        MESheader(10, 0) = "X-Rule"
        MESheader(10, 1) = "None"

        'X-Rule

        Try
            SendData = JsonHelper.ToJson(mes1)
            AppendInfoToTextBox("发送上传信息到MES：" & SendData)
            '
            If testMode = True Then
                result = TextBox_BaseInfo.Text
                AppendInfoToTextBox("测试模式MES Base数据：" & SendData)
            Else

                If newset(0) = False Then '’
                    result = ""
                Else
                    result = MakeRequest3(machineInfo.MES_UploadAddress, "", 10000, MESheader, SendData)
                    AppendInfoToTextBox("数据上传结果:" & result)
                    Dim returndata As MesReturnData = JsonHelper.DeserializeJson(Of MesReturnData)(result)
                End If
            End If
        Catch ex As Exception
            AppendInfoToTextBox(ex.Message.ToString & ex.StackTrace.ToString)
        End Try
        Return result
    End Function

    Public Function MakeRequest3(URL As String, parameters As String, timeOut As Integer, header(,) As String, PostData As String) As String
        Dim responseValue As String = String.Empty
        Try
            Dim url1 As Uri = New Uri(URL)

            Dim request As HttpWebRequest = CType(WebRequest.Create(url1), HttpWebRequest)
            request.Method = "POST" 'HttpVerb.GETS.ToString
            request.ContentLength = 0
            request.ContentType = "application/json"

            For i As Integer = 0 To header.GetLength(0) - 1
                request.Headers.Add(header(i, 0), header(i, 1))
            Next

            request.Timeout = timeOut

            If String.IsNullOrEmpty(PostData) = False Then
                Dim bytes() As Byte = Encoding.UTF8.GetBytes(PostData)
                request.ContentLength = bytes.Length
                Using writeStream As Stream = request.GetRequestStream()
                    writeStream.Write(bytes, 0, bytes.Length)
                End Using
            End If

            Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)

                If response.StatusCode <> HttpStatusCode.OK Then
                    Dim message As String = String.Format("Request failed. Received HTTP {0}", response.StatusCode)
                    AppendInfoToTextBox("MES访问异常：" & message)
                End If
                Using responseStream As Stream = response.GetResponseStream()
                    If responseStream IsNot Nothing Then
                        Using reader As StreamReader = New StreamReader(responseStream)
                            responseValue = reader.ReadToEnd()
                        End Using
                    End If
                End Using
            End Using
        Catch ex As Exception
            'MsgBox(ex.Message)
            AppendInfoToTextBox(ex.Message)
            responseValue = ""
        End Try
        Return responseValue
    End Function

    ''' MES数据发送与接收
    Private Function MES_Secversend(ByVal SendPosData As String, ByVal ServerEndPoint As String)
        Try
            AddInfoToMES("发送的信息：" & SendPosData & vbCrLf)
            Dim client = New RestClient()
            client.EndPoint = ServerEndPoint                '访问地址http://10.159.64.29:901/Service.svc/PUSHDATA/1
            client.Method = HttpVerb.POST
            client.PostData = SendPosData                   '发送数据"{postData: value}"
            Dim json = client.MakeRequest()                 '接受数据
            AddInfoToMES("接受的信息：" & json & vbCrLf)
            Dim Recvedata() As String = json.Split(vbCrLf)            '分解接受的信息
            Return Recvedata
        Catch ex As Exception
            Return False
            MsgBox("MES数据传送错误:" & vbCrLf & ex.Message.ToString)
        End Try
    End Function

    Protected Sub AddInfoToMES(ByVal s As String)         '保存MES数据
        Try
            If (TxtResult_MES.InvokeRequired) Then
                Dim cb As AddRecvToText = New AddRecvToText(AddressOf AddInfoToMES)
                Invoke(cb, s)
            Else
                Dim LogPath As String = CD_Dir & "上位机资料\log\" & Format(Date.Now.Date, "yyyyMMdd") & "\"
                TxtResult_MES.AppendText(s + vbCrLf)
                Dim openresult As Boolean = Exists(LogPath & "MES_Result_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt")
                Dim fileNum As Integer
                fileNum = FreeFile()
                If openresult = False Then
                    Directory.CreateDirectory(LogPath)
                    FileOpen(fileNum, LogPath & "MES_Result_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt", OpenMode.Append)
                    FileClose(fileNum)
                End If
                '文件名
                Dim strSaveFilename As String
                strSaveFilename = LogPath & "MES_Result_" & Format(Date.Now.Date, "yyyyMMdd") & ".txt"

                '打开文件
                FileOpen(fileNum, strSaveFilename, OpenMode.Append)

                '存储文件title
                Print(fileNum, "MES_Result_" & Date.Now & vbTab)

                '存储到文件中
                Print(fileNum, s & vbCrLf)
                '关闭文件
                FileClose(fileNum)
            End If
        Catch ex As Exception
            MsgBox("AddInfoToMES:" & ex.Message.ToString)
        End Try
    End Sub

#End Region

    Private Sub CheckUploadEXE_Tick(sender As Object, e As EventArgs) Handles CheckUploadEXE.Tick
        CheckUploadEXE.Enabled = False
        Try
            mainInfo.RunTime += 1
            'bootTime.Text = mainInfo.RunTime
            If newset(0) = False And newset(7) = False Then
                TextBox8_UpLoadStatus.BackColor = Color.Red
                TextBox8_UpLoadStatus.Text = "关闭"
            ElseIf newset(0) = True And newset(7) = False Then
                'TextBox8_UpLoadStatus.BackColor = Color.Lime
                'TextBox8_UpLoadStatus.Text = "MES开启"
                'Dim ITOTthread As Thread = New Thread(AddressOf OpenLCFCITOTProcess)
                'ITOTthread.Start()
            ElseIf newset(0) = False And newset(7) = True Then
                TextBox8_UpLoadStatus.BackColor = Color.Lime
                TextBox8_UpLoadStatus.Text = "OPC开启"
                Dim Uploadthread As Thread = New Thread(AddressOf OpenUploadProcess)
                Uploadthread.Start()
            ElseIf newset(0) = True And newset(7) = True Then
                TextBox8_UpLoadStatus.BackColor = Color.Lime
                TextBox8_UpLoadStatus.Text = "MES/OPC开启"
                'Dim ITOTthread As Thread = New Thread(AddressOf OpenLCFCITOTProcess)
                'ITOTthread.Start()
                Dim Uploadthread As Thread = New Thread(AddressOf OpenUploadProcess)
                Uploadthread.Start()
            End If
            OPC_RefreshData_ProductionData()
        Catch ex As Exception
            AppendInfoToTextBox("CheckUploadEXE_Tick:" & ex.Message.ToString)
        End Try
        CheckUploadEXE.Enabled = True
    End Sub

    Private Sub TimerRubish_Tick(sender As Object, e As EventArgs) Handles TimerRubish.Tick
        GC.Collect()
    End Sub

    Private Sub Count_Clear_Click_1(sender As Object, e As EventArgs) Handles Count_Clear.Click
        Try
            If MsgBox("确定清除生产数据？", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
            Else
                GoTo d
            End If
            Todaycount.ScanSN = 0
            Todaycount.NGCount = 0
            Todaycount.PassCount = 0
            Todaycount.SCount = 0
            Todaycount.ScrewCount = 0
            Todaycount.ScrewFailed1 = 0
            Todaycount.ScrewFailed2 = 0
            Todaycount.ScrewFailed3 = 0
            Todaycount.ScrewFailed4 = 0
            Todaycount.ScrewFailed5 = 0
            Todaycount.ScrewFailed6 = 0
            Todaycount.ScrewFailed7 = 0
            Todaycount.ScrewFailed8 = 0
            Todaycount.ScrewFailed9 = 0
            Todaycount.ScrewFailed10 = 0
            Todaycount.ScrewFailed11 = 0
            Todaycount.ScrewFailed12 = 0
            Todaycount.ScrewFailed13 = 0
            Todaycount.ScrewFailed14 = 0
            Todaycount.ScrewFailed15 = 0
            Todaycount.ScrewFailed16 = 0
            Todaycount.ScrewFailed17 = 0
            Todaycount.ScrewFailed18 = 0
            Todaycount.ScrewFailed19 = 0
            Todaycount.ScrewFailed20 = 0
            Todaycount.ScrewFailed21 = 0
            Todaycount.ScrewFailed22 = 0
            Todaycount.ScrewFailed23 = 0
            Todaycount.ScrewFailed24 = 0
            Todaycount.ScrewFailed25 = 0
            Todaycount.ScrewFailed26 = 0
            Todaycount.ScrewFailed27 = 0
            Todaycount.ScrewFailed28 = 0
            Todaycount.ScrewFailed29 = 0
            Todaycount.ScrewFailed30 = 0
            Todaycount.ScrewFailed31 = 0
            Todaycount.ScrewFailed32 = 0
            Todaycount.ScrewFailed33 = 0
            Todaycount.ScrewFailed34 = 0
            Todaycount.ScrewFailed35 = 0
            Todaycount1.SNCount = 0
            Todaycount1.SN_Check = 0

            TextBox1.Text = Todaycount.ScanSN.ToString

            PassCount.Text = Todaycount.PassCount.ToString
            NGCount.Text = Todaycount.NGCount.ToString
            SCount.Text = Todaycount.SCount.ToString
            ScrewCount.Text = Todaycount.ScrewCount.ToString
            ScrewFailed1.Text = Todaycount.ScrewFailed1.ToString
            ScrewFailed2.Text = Todaycount.ScrewFailed2.ToString
            ScrewFailed3.Text = Todaycount.ScrewFailed3.ToString
            ScrewFailed4.Text = Todaycount.ScrewFailed4.ToString
            ScrewFailed5.Text = Todaycount.ScrewFailed5.ToString
            ScrewFailed6.Text = Todaycount.ScrewFailed6.ToString
            ScrewFailed7.Text = Todaycount.ScrewFailed7.ToString
            ScrewFailed8.Text = Todaycount.ScrewFailed8.ToString
            ScrewFailed9.Text = Todaycount.ScrewFailed9.ToString
            ScrewFailed10.Text = Todaycount.ScrewFailed10.ToString
            ScrewFailed11.Text = Todaycount.ScrewFailed11.ToString
            ScrewFailed12.Text = Todaycount.ScrewFailed12.ToString
            ScrewFailed13.Text = Todaycount.ScrewFailed13.ToString
            ScrewFailed14.Text = Todaycount.ScrewFailed14.ToString
            ScrewFailed15.Text = Todaycount.ScrewFailed15.ToString
            ScrewFailed16.Text = Todaycount.ScrewFailed16.ToString
            ScrewFailed17.Text = Todaycount.ScrewFailed17.ToString
            ScrewFailed18.Text = Todaycount.ScrewFailed18.ToString
            ScrewFailed19.Text = Todaycount.ScrewFailed19.ToString
            ScrewFailed20.Text = Todaycount.ScrewFailed20.ToString
            ScrewFailed21.Text = Todaycount.ScrewFailed21.ToString
            ScrewFailed22.Text = Todaycount.ScrewFailed22.ToString
            ScrewFailed23.Text = Todaycount.ScrewFailed23.ToString
            ScrewFailed24.Text = Todaycount.ScrewFailed24.ToString
            ScrewFailed25.Text = Todaycount.ScrewFailed25.ToString
            ScrewFailed26.Text = Todaycount.ScrewFailed26.ToString
            ScrewFailed27.Text = Todaycount.ScrewFailed27.ToString
            ScrewFailed28.Text = Todaycount.ScrewFailed28.ToString
            ScrewFailed29.Text = Todaycount.ScrewFailed29.ToString
            ScrewFailed30.Text = Todaycount.ScrewFailed30.ToString
            TxtBlowNum.Text = Todaycount.ScrewFailed35.ToString
            Todaycount.SuctionCount = 0
            Todaycount.CycleTime = 0
            Todaycount.PCSFailedCount = 0
            Todaycount.SuctionCount = 0

            SuctionCount.Text = Todaycount.SuctionCount
            TextBox_CT.Text = 0
            TextBox_PCSFailed.Text = 0
            Suction = 0
            IsFirstSend = 1

            If Exists(gProDataPath & "\count.txt") Then
                '       Kill(filepath & "\count.txt")
                FileOpen(file_num_count, gProDataPath & "\count.txt", OpenMode.Random, , , RecordLength:=Len(Todaycount))
                FilePut(file_num_count, Todaycount)
                FileClose(file_num_count)
            End If

            If Exists(gProDataPath & "\count1.txt") Then
                '      Kill(filepath & TCmbPro.Text & "\count.txt")
                FileOpen(file_num_count1, gProDataPath & "\count1.txt", OpenMode.Random, , , RecordLength:=Len(Todaycount))
                FilePut(file_num_count1, Todaycount1)
                FileClose(file_num_count1)
            End If
d:
        Catch ex As Exception
            AppendInfoToTextBox("Count_Clear_Click:" & ex.Message.ToString)
        End Try
    End Sub

    Private Sub Button12_Click_1(sender As Object, e As EventArgs) Handles Button12.Click
        Panel2.BackColor = Color.Lime
        Label26.Text = "报警时间："
        Label13.Text = "报警信息："
        OPC_Refresh_Alarm(0)
    End Sub

    Public Sub InitMaintanceInfo()
        Try
            Dim sql As String = "select * from Maintainace"
            Dim ds As DataSet = New DataSet
            ds = SearchMysql(sql)
            For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                If ds.Tables(0).Rows(i)("MaintanceTime").ToString <> "" Then
                    Dim time As DateTime = ds.Tables(0).Rows(i)("MaintanceTime").ToString
                    Dim cycTimes As Integer = ds.Tables(0).Rows(i)("MaintanceCycle").ToString
                    If ds.Tables(0).Rows(i)("MaintanceType").ToString = "1" Then
                        MaintainInfo.Feeder_preMaintanceTime = time
                        MaintainInfo.Feeder_MaintanceCycle = cycTimes
                    ElseIf ds.Tables(0).Rows(i)("MaintanceType").ToString = "2" Then
                        MaintainInfo.Screwdriver_preMaintanceTime = time
                        MaintainInfo.Screwdriver_MaintanceCycle = cycTimes
                    ElseIf ds.Tables(0).Rows(i)("MaintanceType").ToString = "3" Then
                        MaintainInfo.Motor_preMaintanceTime = time
                        MaintainInfo.Motor_MaintanceCycle = cycTimes
                    ElseIf ds.Tables(0).Rows(i)("MaintanceType").ToString = "4" Then
                        MaintainInfo.Nozzle_preMaintanceTime = time
                        MaintainInfo.Nozzle_MaintanceCycle = cycTimes
                    ElseIf ds.Tables(0).Rows(i)("MaintanceType").ToString = "5" Then
                        MaintainInfo.Screw_preMaintanceTime = time
                        MaintainInfo.Screw_MaintanceCycle = cycTimes
                    ElseIf ds.Tables(0).Rows(i)("MaintanceType").ToString = "6" Then
                        MaintainInfo.Cable_preMaintanceTime = time
                        MaintainInfo.Cable_MaintanceCycle = cycTimes
                    ElseIf ds.Tables(0).Rows(i)("MaintanceType").ToString = "7" Then
                        MaintainInfo.Blet_preMaintanceTime = time
                        MaintainInfo.Blet_MaintanceCycle = cycTimes
                    ElseIf ds.Tables(0).Rows(i)("MaintanceType").ToString = "8" Then
                        MaintainInfo.Clean_preMaintanceTime = time
                        MaintainInfo.Clean_MaintanceCycle = cycTimes
                    ElseIf ds.Tables(0).Rows(i)("MaintanceType").ToString = "9" Then
                        MaintainInfo.Feeder_preMaintanceTime = time
                        MaintainInfo.Feeder_MaintanceCycle = cycTimes
                    End If
                End If
            Next

            OPC_Refresh_Maintance()
        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString & ex.StackTrace.ToString, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

#Region "OPC 数据上传相关"

    Dim OPC_PREDATA_PARA As String = ""

    ''' <summary>
    ''' OPC 数据更新parameter-InitSetting
    ''' </summary>
    Public Sub OPC_RefreshData_Parameter()
        Try
            'OPC数据刷新
            OPC_Machine_Parameter.Biggist_Distance = Pget(2).ZPosCompensate
            OPC_Machine_Parameter.CCD_Enabel = IIf(newset(8) = False, 0, 1)
            OPC_Machine_Parameter.DeviationRange_X = Pget(2).XPosCompensate & "~" & Pget(2).YPosCompensate
            OPC_Machine_Parameter.Feeder1_CompenstateX = Pget(0).XPosCompensate
            OPC_Machine_Parameter.Feeder1_CompenstateY = Pget(0).YPosCompensate
            OPC_Machine_Parameter.Feeder1_CompenstateZ = Pget(0).ZPosCompensate

            OPC_Machine_Parameter.Feeder2_CompenstateX = Pget(1).XPosCompensate
            OPC_Machine_Parameter.Feeder2_CompenstateY = Pget(1).YPosCompensate
            OPC_Machine_Parameter.Feeder2_CompenstateZ = Pget(1).ZPosCompensate

            OPC_Machine_Parameter.Feeder_Choose1 = PointPara(0).feeder
            OPC_Machine_Parameter.Feeder_Choose2 = PointPara(1).feeder
            OPC_Machine_Parameter.Feeder_Choose3 = PointPara(2).feeder
            OPC_Machine_Parameter.Feeder_Choose4 = PointPara(3).feeder
            OPC_Machine_Parameter.Feeder_Choose5 = PointPara(4).feeder

            OPC_Machine_Parameter.IOT_Upload = IIf(newset(7) = False, 0, 1)
            OPC_Machine_Parameter.MES_Upload = IIf(newset(0) = False, 0, 1)
            OPC_Machine_Parameter.Online_Station = CurScrewPara.Online_Mod

            '曝光值在相机加载时赋值
            'OPC_Machine_Parameter.Photo1_Exposure = 0
            'OPC_Machine_Parameter.Photo2_Exposure = 0
            'OPC_Machine_Parameter.Photo3_Exposure = 0

            OPC_Machine_Parameter.Photo_Displacement = Pget(6).YPosCompensate

            OPC_Machine_Parameter.Production = Chanpin
            OPC_Machine_Parameter.Retry_Times = Pget(3).YPosCompensate

            OPC_Machine_Parameter.Screw1_CompenstateX = Pset(0).XPosCompensate
            OPC_Machine_Parameter.Screw1_CompenstateY = Pset(0).YPosCompensate
            OPC_Machine_Parameter.Screw1_CompenstateZ = Pset(0).ZPosCompensate
            OPC_Machine_Parameter.Screw1_CompenstateZ = Pset(0).RPosCompensate

            OPC_Machine_Parameter.Screw2_CompenstateX = Pset(1).XPosCompensate
            OPC_Machine_Parameter.Screw2_CompenstateY = Pset(1).YPosCompensate
            OPC_Machine_Parameter.Screw2_CompenstateZ = Pset(1).ZPosCompensate
            OPC_Machine_Parameter.Screw2_CompenstateZ = Pset(1).RPosCompensate

            OPC_Machine_Parameter.Screw3_CompenstateX = Pset(2).XPosCompensate
            OPC_Machine_Parameter.Screw3_CompenstateY = Pset(2).YPosCompensate
            OPC_Machine_Parameter.Screw3_CompenstateZ = Pset(2).ZPosCompensate
            OPC_Machine_Parameter.Screw3_CompenstateZ = Pset(2).RPosCompensate

            OPC_Machine_Parameter.Screw4_CompenstateX = Pset(3).XPosCompensate
            OPC_Machine_Parameter.Screw4_CompenstateY = Pset(3).YPosCompensate
            OPC_Machine_Parameter.Screw4_CompenstateZ = Pset(3).ZPosCompensate
            OPC_Machine_Parameter.Screw4_CompenstateZ = Pset(3).RPosCompensate

            OPC_Machine_Parameter.Screw5_CompenstateX = Pset(4).XPosCompensate
            OPC_Machine_Parameter.Screw5_CompenstateY = Pset(4).YPosCompensate
            OPC_Machine_Parameter.Screw5_CompenstateZ = Pset(4).ZPosCompensate
            OPC_Machine_Parameter.Screw5_CompenstateZ = Pset(4).RPosCompensate

            OPC_Machine_Parameter.Screw_Model = CurScrewPara.ScrewSN
            OPC_Machine_Parameter.Screw_Number = CurScrewPara.PointCount

            OPC_Machine_Parameter.Torsion_Set1 = PointPara(0).torque
            OPC_Machine_Parameter.Torsion_Set2 = PointPara(1).torque
            OPC_Machine_Parameter.Torsion_Set3 = PointPara(2).torque
            OPC_Machine_Parameter.Torsion_Set4 = PointPara(3).torque
            OPC_Machine_Parameter.Torsion_Set5 = PointPara(4).torque

            OPC_Machine_Parameter.Whether_Disabled1 = IIf(PointPara(0).diable = False, 0, 1)
            OPC_Machine_Parameter.Whether_Disabled2 = IIf(PointPara(1).diable = False, 0, 1)
            OPC_Machine_Parameter.Whether_Disabled3 = IIf(PointPara(2).diable = False, 0, 1)
            OPC_Machine_Parameter.Whether_Disabled4 = IIf(PointPara(3).diable = False, 0, 1)
            OPC_Machine_Parameter.Whether_Disabled5 = IIf(PointPara(4).diable = False, 0, 1)
            Dim data As String = gjson.ToJson(OPC_Machine_Parameter)
            UploadMessage(data, "Parameter")
            OPC_PREDATA_PARA = data
        Catch ex As Exception
            AppendInfoToTextBox("OPC parameter Err:" & ex.Message & ex.StackTrace)
        End Try
    End Sub

    Dim OPC_PREDATA_Sensor As String = ""

    ''' <summary>
    ''' OPC 数据更新Sensor
    ''' </summary>
    ''' <param name="dataInput"></param>
    ''' <param name="dataOutput"></param>
    Public Sub OPC_RefreshData_Sensor(ByVal dataInput As Integer, ByVal dataOutput As Integer)
        Try
            Dim InputIO(23), OutputIO(15), i As Integer
            For i = 0 To InputIO.Length - 1
                InputIO(i) = dataInput >> i And 1
            Next
            For i = 0 To OutputIO.Length - 1
                OutputIO(i) = dataOutput >> i And 1
            Next

            'Input
            OPC_Machine_Sensor.Barometer_Signal = InputIO(10) 'DI 10
            OPC_Machine_Sensor.Direction = InputIO(4) 'DI 4
            OPC_Machine_Sensor.DoorGuard = InputIO(1) 'DI 1

            '  OPC_Machine_Sensor.Emergency = InputIO(10) 接受信息中赋值
            OPC_Machine_Sensor.Location_Sensor1 = InputIO(6) 'DI6
            OPC_Machine_Sensor.Location_Sensor2 = InputIO(7) 'DI7
            OPC_Machine_Sensor.Output_Sensor = InputIO(20) 'DI20
            OPC_Machine_Sensor.Outside_Sensor = InputIO(16) 'DI16

            OPC_Machine_Sensor.Reset = InputIO(3) 'DI3
            OPC_Machine_Sensor.Start = InputIO(0) 'DI 0
            OPC_Machine_Sensor.Vacuum_Signal = InputIO(11) ' DI 11

            'output
            OPC_Machine_Sensor.Belt_Signal = OutputIO(0) 'DO 0
            OPC_Machine_Sensor.Cylinder_Signal = OutputIO(10) 'DO 10
            OPC_Machine_Sensor.Pause = OutputIO(4) 'DO 4
            '
            If EQ_Status <> Equipment_Status._MAINTANCE Then '非保养状态时，以机器人IO状态判断
                If OutputIO(14) = 1 Then '蜂鸣器
                    EQ_Status = Equipment_Status._ALARM
                    TextBox_RunStatus.Text = "ALARM"
                    TextBox_RunStatus.BackColor = Color.Red
                End If
                If OutputIO(4) = 1 Then '暂停
                    EQ_Status = Equipment_Status._PAUSE
                    TextBox_RunStatus.Text = "STOP"
                    TextBox_RunStatus.BackColor = Color.Yellow
                Else
                    If OutputIO(3) = 1 Then '运行
                        EQ_Status = Equipment_Status._RUN
                        TextBox_RunStatus.Text = "RUN"
                        TextBox_RunStatus.BackColor = Color.Lime
                    End If
                End If
            End If

            Dim data As String = gjson.ToJson(OPC_Machine_Sensor)
            If OPC_PREDATA_Sensor <> data Then
                OPC_PREDATA_Sensor = data
                UploadMessage(data, "Singles")
            End If
        Catch ex As Exception
            AppendInfoToTextBox("OPC parameter Err:" & ex.Message & ex.StackTrace)
        End Try
    End Sub

    Dim OPC_PREDATA_ProdData As String = ""

    ''' <summary>
    ''' OPC 生产数据更新-CheckUploadEXE中/S执行
    ''' </summary>
    Public Sub OPC_RefreshData_ProductionData()
        Try
            '  OPC_Machine_ProductionData.CT = Todaycount.CycleTime
            OPC_Machine_ProductionData.CT = Format(Val(TextBox_CT.Text.Split("s")(0)), "0.00")
            OPC_Machine_ProductionData.Total_Attached = Todaycount.ScrewCount
            OPC_Machine_ProductionData.Total_NG_Attached = Todaycount.SCount
            OPC_Machine_ProductionData.Total_NG_Product = Todaycount.PCSFailedCount
            OPC_Machine_ProductionData.Total_Product = Todaycount.PassCount
            OPC_Machine_ProductionData.Vaccum_Failed = Todaycount.SuctionCount
            OPC_Machine_ProductionData.Vacuum_Erro = Todaycount.SuctionCount
            OPC_Machine_ProductionData.Vision_Failed = Todaycount.NGCount
            OPC_Machine_ProductionData.Yield_Product = IIf(Todaycount.PassCount > 0, 100 * (1 - (Todaycount.PCSFailedCount / Todaycount.PassCount)), 100)
            OPC_Machine_ProductionData.Yield_Screw = IIf(Todaycount.ScrewCount > 0, 100 * (1 - (Todaycount.SCount / Todaycount.ScrewCount)), 100)

            Dim data As String = gjson.ToJson(OPC_Machine_ProductionData)
            If OPC_PREDATA_ProdData <> data Then
                OPC_PREDATA_ProdData = data
                UploadMessage(data, "TodayData")
            End If
        Catch ex As Exception
            AppendInfoToTextBox("OPC parameter Err:" & ex.Message & ex.StackTrace)
        End Try
    End Sub

    Dim OPC_PREDATA_Status As String = ""

    ''' <summary>
    ''' OPC 设备状态数据更新
    ''' </summary>
    Private Sub OPC_RefreshData_Status()
        Try
            OPC_Machine_Status.Equipment_State = EQ_Status
            OPC_Machine_Status.MES_Connection = IIf(newset(0), 1, 0)

            If Button_LJ.Text = "关闭" Then
                OPC_Machine_Status.Online_Status = 0
            Else
                OPC_Machine_Status.Online_Status = 1
            End If

            If TextBox_OPID.Text = "未登陆" Or TextBox_OPID.Text = "" Then
                OPC_Machine_Status.OperatorID = ""
            Else
                OPC_Machine_Status.OperatorID = TextBox_OPID.Text
            End If
            If Button_PLC.Text = "PLC联机" Then
                OPC_Machine_Status.PLC_Status = 1
            Else
                OPC_Machine_Status.PLC_Status = 0
            End If

            If EQ_Status <> Equipment_Status._STARTUP And EQ_Status <> Equipment_Status._MAINTANCE Then
                If EQ_Status = Equipment_Status._PAUSE Then
                    OPC_Machine_Status.Robot_Status = 2
                    OPC_Machine_Status.PLC_Status = 2
                Else
                    OPC_Machine_Status.Robot_Status = 1
                    OPC_Machine_Status.PLC_Status = 1
                End If
            Else
                OPC_Machine_Status.Robot_Status = 0
                OPC_Machine_Status.PLC_Status = 0
            End If
            Dim data As String = gjson.ToJson(OPC_Machine_Status)
            If OPC_PREDATA_Status <> data Then
                OPC_PREDATA_Status = data
                UploadMessage(data, "Status")
            End If
        Catch ex As Exception
            AppendInfoToTextBox("OPC parameter Err:" & ex.Message & ex.StackTrace)
        End Try

    End Sub

    Dim OPC_PREDATA_Info As String = ""

    ''' <summary>
    ''' OPC 设备信息数据更新->loadequipment
    ''' </summary>
    Public Sub OPC_RefreshData_Info()
        Try
            OPC_Machine_Info.Device_ID = EquipmentInfo.MachineID
            OPC_Machine_Info.Equipment_Model = EquipmentInfo.Robot_Version
            OPC_Machine_Info.Equipment_Name = "ScrewingMachine"
            OPC_Machine_Info.Leading_Name = EquipmentInfo.Charge_Name
            OPC_Machine_Info.Leading_Email = EquipmentInfo.Charge_Email
            OPC_Machine_Info.Leading_Telephone = EquipmentInfo.Charge_Telephone
            OPC_Machine_Info.Line = EquipmentInfo.LineID
            OPC_Machine_Info.Manufacturer_Name = EquipmentInfo.Robot_Company
            OPC_Machine_Info.Manufacture_Date = EquipmentInfo.Robot_Datatime
            OPC_Machine_Info.Software_Version = EquipmentInfo.SoftVersion
            OPC_Machine_Info.Station = EquipmentInfo.StationID

            Dim data As String = gjson.ToJson(OPC_Machine_Info)
            If OPC_PREDATA_Info <> data Then
                OPC_PREDATA_Info = data
                UploadMessage(data, "MachineInfo")
            End If
        Catch ex As Exception
            AppendInfoToTextBox("OPC Info Err:" & ex.Message & ex.StackTrace)
        End Try
    End Sub

    Dim OPC_PREDATA_Maintance As String = ""

    ''' <summary>
    '''  OPC 设备保养数据更新->每天8点/20点更新
    ''' </summary>
    Public Sub OPC_Refresh_Maintance()
        Try
            '0:已保养；1：需要保养；2保养逾期
            Dim mtTime As DateTime = DateTime.Now '当前时间
            Dim oldTime As DateTime = DateTime.Now '上次保养时间
            Dim offsetDays As Integer
            '1.供料器保养
            OPC_Machine_Maintance.Feeder.FeederMaintain_Date = IIf(MaintainInfo.Feeder_preMaintanceTime = "", "1900-1-1 00:00:00", MaintainInfo.Feeder_preMaintanceTime)
            OPC_Machine_Maintance.Feeder.FeederMaintain_Period = MaintainInfo.Feeder_MaintanceCycle  '保养周期

            Try
                oldTime = MaintainInfo.Feeder_preMaintanceTime
            Catch ex As Exception
                MaintainInfo.Feeder_preMaintanceTime = DateTime.Now.ToString
                oldTime = DateTime.Now.ToString
            End Try
            offsetDays = OPC_Machine_Maintance.Feeder.FeederMaintain_Period - (mtTime - oldTime).Days
            If offsetDays > 0 Then
                OPC_Machine_Maintance.Feeder.FeederWetherNeed_Maintain = 0
                OPC_Machine_Maintance.Feeder.FeederMaintain_Status = 0
            ElseIf offsetDays = 0 Then
                OPC_Machine_Maintance.Feeder.FeederWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Feeder.FeederMaintain_Status = 1
            Else
                OPC_Machine_Maintance.Feeder.FeederWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Feeder.FeederMaintain_Status = 2
            End If

            '2.皮带保养
            OPC_Machine_Maintance.Belt.BeltMaintain_Date = IIf(MaintainInfo.Blet_preMaintanceTime = "", "1900-1-1 00:00:00", MaintainInfo.Blet_preMaintanceTime)
            OPC_Machine_Maintance.Belt.BeltMaintain_Period = MaintainInfo.Blet_MaintanceCycle '保养周期
            Try
                oldTime = MaintainInfo.Blet_preMaintanceTime
            Catch ex As Exception
                MaintainInfo.Blet_preMaintanceTime = DateTime.Now.ToString
                oldTime = DateTime.Now.ToString
            End Try
            offsetDays = OPC_Machine_Maintance.Belt.BeltMaintain_Period - (mtTime - oldTime).Days
            If offsetDays > 0 Then
                OPC_Machine_Maintance.Belt.BeltWetherNeed_Maintain = 0
                OPC_Machine_Maintance.Belt.BeltMaintain_Status = 0
            ElseIf offsetDays = 0 Then
                OPC_Machine_Maintance.Belt.BeltWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Belt.BeltMaintain_Status = 1
            Else
                OPC_Machine_Maintance.Belt.BeltWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Belt.BeltMaintain_Status = 2
            End If

            '3.线缆保养
            OPC_Machine_Maintance.Cable.CableMaintain_Date = IIf(MaintainInfo.Cable_preMaintanceTime = "", "1900-1-1 00:00:00", MaintainInfo.Cable_preMaintanceTime)
            OPC_Machine_Maintance.Cable.CableMaintain_Period = MaintainInfo.Cable_MaintanceCycle '保养周期
            Try
                oldTime = MaintainInfo.Cable_preMaintanceTime
            Catch ex As Exception
                MaintainInfo.Cable_preMaintanceTime = DateTime.Now.ToString
                oldTime = DateTime.Now.ToString
            End Try
            offsetDays = OPC_Machine_Maintance.Cable.CableMaintain_Period - (mtTime - oldTime).Days
            If offsetDays > 0 Then
                OPC_Machine_Maintance.Cable.CableWetherNeed_Maintain = 0
                OPC_Machine_Maintance.Cable.CableMaintain_Status = 0
            ElseIf offsetDays = 0 Then
                OPC_Machine_Maintance.Cable.CableWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Cable.CableMaintain_Status = 1
            Else
                OPC_Machine_Maintance.Cable.CableWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Cable.CableMaintain_Status = 2
            End If

            '4.清洁保养
            OPC_Machine_Maintance.Clean.CleanMaintain_Date = IIf(MaintainInfo.Clean_preMaintanceTime = "", "1900-1-1 00:00:00", MaintainInfo.Clean_preMaintanceTime)
            OPC_Machine_Maintance.Clean.CleanMaintain_Period = MaintainInfo.Clean_MaintanceCycle '保养周期
            Try
                oldTime = MaintainInfo.Clean_preMaintanceTime
            Catch ex As Exception
                MaintainInfo.Clean_preMaintanceTime = DateTime.Now.ToString
                oldTime = DateTime.Now.ToString
            End Try
            offsetDays = OPC_Machine_Maintance.Clean.CleanMaintain_Period - (mtTime - oldTime).Days
            If offsetDays > 0 Then
                OPC_Machine_Maintance.Clean.CleanWetherNeed_Maintain = 0
                OPC_Machine_Maintance.Clean.CleanMaintain_Status = 0
            ElseIf offsetDays = 0 Then
                OPC_Machine_Maintance.Clean.CleanWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Clean.CleanMaintain_Status = 1
            Else
                OPC_Machine_Maintance.Clean.CleanWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Clean.CleanMaintain_Status = 2
            End If

            '5.马达保养
            OPC_Machine_Maintance.Motor.MotorMaintain_Date = IIf(MaintainInfo.Motor_preMaintanceTime = "", "1900-1-1 00:00:00", MaintainInfo.Motor_preMaintanceTime)
            OPC_Machine_Maintance.Motor.MotorMaintain_Period = MaintainInfo.Motor_MaintanceCycle '保养周期
            Try
                oldTime = MaintainInfo.Motor_preMaintanceTime
            Catch ex As Exception
                MaintainInfo.Motor_preMaintanceTime = DateTime.Now.ToString
                oldTime = DateTime.Now.ToString
            End Try
            offsetDays = OPC_Machine_Maintance.Motor.MotorMaintain_Period - (mtTime - oldTime).Days
            If offsetDays > 0 Then
                OPC_Machine_Maintance.Motor.MotorWetherNeed_Maintain = 0
                OPC_Machine_Maintance.Motor.MotorMaintain_Status = 0
            ElseIf offsetDays = 0 Then
                OPC_Machine_Maintance.Motor.MotorWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Motor.MotorMaintain_Status = 1
            Else
                OPC_Machine_Maintance.Motor.MotorWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Motor.MotorMaintain_Status = 2
            End If

            '6.机器人保养
            OPC_Machine_Maintance.Robot.RobotMaintain_Date = IIf(MaintainInfo.Robot_preMaintanceTime = "", "1900-1-1 00:00:00", MaintainInfo.Robot_preMaintanceTime)
            OPC_Machine_Maintance.Robot.RobotMaintain_Period = MaintainInfo.Robot_MaintanceCycle '保养周期
            Try
                oldTime = MaintainInfo.Robot_preMaintanceTime
            Catch ex As Exception
                MaintainInfo.Robot_preMaintanceTime = DateTime.Now.ToString
                oldTime = DateTime.Now.ToString
            End Try
            offsetDays = OPC_Machine_Maintance.Robot.RobotMaintain_Period - (mtTime - oldTime).Days
            If offsetDays > 0 Then
                OPC_Machine_Maintance.Robot.RobotWetherNeed_Maintain = 0
                OPC_Machine_Maintance.Robot.RobotMaintain_Status = 0
            ElseIf offsetDays = 0 Then
                OPC_Machine_Maintance.Robot.RobotWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Robot.RobotMaintain_Status = 1
            Else
                OPC_Machine_Maintance.Robot.RobotWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Robot.RobotMaintain_Status = 2
            End If

            '7.螺丝松动保养
            OPC_Machine_Maintance.Screw.ScrewMaintain_Date = IIf(MaintainInfo.Screw_preMaintanceTime = "", "1900-1-1 00:00:00", MaintainInfo.Screw_preMaintanceTime)
            OPC_Machine_Maintance.Screw.ScrewMaintain_Period = MaintainInfo.Screw_MaintanceCycle '保养周期
            Try
                oldTime = MaintainInfo.Screw_preMaintanceTime
            Catch ex As Exception
                MaintainInfo.Screw_preMaintanceTime = DateTime.Now.ToString
                oldTime = DateTime.Now.ToString
            End Try
            offsetDays = OPC_Machine_Maintance.Screw.ScrewMaintain_Period - (mtTime - oldTime).Days
            If offsetDays > 0 Then
                OPC_Machine_Maintance.Screw.ScrewWetherNeed_Maintain = 0
                OPC_Machine_Maintance.Screw.ScrewMaintain_Status = 0
            ElseIf offsetDays = 0 Then
                OPC_Machine_Maintance.Screw.ScrewWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Screw.ScrewMaintain_Status = 1
            Else
                OPC_Machine_Maintance.Screw.ScrewWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Screw.ScrewMaintain_Status = 2
            End If

            '8.起子头保养
            OPC_Machine_Maintance.Screwdriver.ScrewdriverMaintain_Date = IIf(MaintainInfo.Screwdriver_preMaintanceTime = "", "1900-1-1 00:00:00", MaintainInfo.Screwdriver_preMaintanceTime)
            OPC_Machine_Maintance.Screwdriver.ScrewdriverMaintain_Period = MaintainInfo.Screwdriver_MaintanceCycle '保养周期
            Try
                oldTime = MaintainInfo.Screwdriver_preMaintanceTime
            Catch ex As Exception
                MaintainInfo.Screwdriver_preMaintanceTime = DateTime.Now.ToString
                oldTime = DateTime.Now.ToString
            End Try
            offsetDays = OPC_Machine_Maintance.Screwdriver.ScrewdriverMaintain_Period - (mtTime - oldTime).Days
            If offsetDays > 0 Then
                OPC_Machine_Maintance.Screwdriver.ScrewdriverWetherNeed_Maintain = 0
                OPC_Machine_Maintance.Screwdriver.ScrewdriverMaintain_Status = 0
            ElseIf offsetDays = 0 Then
                OPC_Machine_Maintance.Screwdriver.ScrewdriverWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Screwdriver.ScrewdriverMaintain_Status = 1
            Else
                OPC_Machine_Maintance.Screwdriver.ScrewdriverWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Screwdriver.ScrewdriverMaintain_Status = 2
            End If

            '9.吸嘴保养
            OPC_Machine_Maintance.Suction_nozzle.Suction_nozzleMaintain_Date = IIf(MaintainInfo.Nozzle_preMaintanceTime = "", "1900-1-1 00:00:00", MaintainInfo.Nozzle_preMaintanceTime)
            OPC_Machine_Maintance.Suction_nozzle.Suction_nozzleMaintain_Period = MaintainInfo.Nozzle_MaintanceCycle '保养周期
            Try
                oldTime = MaintainInfo.Nozzle_preMaintanceTime
            Catch ex As Exception
                MaintainInfo.Nozzle_preMaintanceTime = DateTime.Now.ToString
                oldTime = DateTime.Now.ToString
            End Try
            offsetDays = OPC_Machine_Maintance.Suction_nozzle.Suction_nozzleMaintain_Period - (mtTime - oldTime).Days
            If offsetDays > 0 Then
                OPC_Machine_Maintance.Suction_nozzle.Suction_nozzleWetherNeed_Maintain = 0
                OPC_Machine_Maintance.Suction_nozzle.Suction_nozzleMaintain_Status = 0
            ElseIf offsetDays = 0 Then
                OPC_Machine_Maintance.Suction_nozzle.Suction_nozzleWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Suction_nozzle.Suction_nozzleMaintain_Status = 1
            Else
                OPC_Machine_Maintance.Suction_nozzle.Suction_nozzleWetherNeed_Maintain = 1
                OPC_Machine_Maintance.Suction_nozzle.Suction_nozzleMaintain_Status = 2
            End If

            Dim data As String = gjson.ToJson(OPC_Machine_Maintance)
            OPC_PREDATA_Maintance = data
            UploadMessage(data, "MaintanceData")
        Catch ex As Exception
            AppendInfoToTextBox("OPC Maintance Err:" & ex.Message & ex.StackTrace)
        End Try
    End Sub

    Dim OPC_PREDATA_Alarm As String = ""

    ''' <summary>
    '''  OPC 设备保养数据更新->接收报警信息时/解除报警时
    ''' </summary>
    ''' <param name="alarmNO"></param>
    Public Sub OPC_Refresh_Alarm(ByVal alarmNO As String)
        Try
            OPC_Machine_Alarm.Alarm_Status = 1
            Select Case alarmNO
                Case 0
                    OPC_Machine_Alarm.Alarm_Node = 0
                    OPC_Machine_Alarm.Alarm_Status = 0
                Case 1
                    OPC_Machine_Alarm.Alarm_Node = OPC_Machine_Alarm.Alarm_Node Or &H1
                Case 2
                    OPC_Machine_Alarm.Alarm_Node = OPC_Machine_Alarm.Alarm_Node Or &H2
                Case 3
                    OPC_Machine_Alarm.Alarm_Node = OPC_Machine_Alarm.Alarm_Node Or &H4
                Case 4
                    OPC_Machine_Alarm.Alarm_Node = OPC_Machine_Alarm.Alarm_Node Or &H8
                Case 5
                    OPC_Machine_Alarm.Alarm_Node = OPC_Machine_Alarm.Alarm_Node Or &H10
                Case 6
                    OPC_Machine_Alarm.Alarm_Node = OPC_Machine_Alarm.Alarm_Node Or &H20
                Case 7
                    OPC_Machine_Alarm.Alarm_Node = OPC_Machine_Alarm.Alarm_Node Or &H40
            End Select

            Dim data As String = gjson.ToJson(OPC_Machine_Alarm)
            If OPC_PREDATA_Alarm <> data Then
                OPC_PREDATA_Alarm = data
                UploadMessage(data, "Warning")
            End If
        Catch ex As Exception
            AppendInfoToTextBox("OPC alarm Err:" & ex.Message & ex.StackTrace)
        End Try
    End Sub

    ''' <summary>
    ''' 生产结束时
    ''' </summary>
    Public Sub OPC_Refresh_ProductionLog()
        Try
            Dim data As String = gjson.ToJson(OPC_Machine_ProductionLog)
            AppendInfoToTextBox("ProductProcess:" & data)
            UploadMessage(data, "ProductProcess")
        Catch ex As Exception
            AppendInfoToTextBox("OPC production log Err:" & ex.Message & ex.StackTrace)
        End Try
    End Sub

    ''' <summary>
    ''' 加料提醒
    ''' </summary>
    Public Sub OPC_Refresh_AddScrew()
        Try
            Dim data As String = gjson.ToJson(OPC_Machine_AddScrew)
            AppendInfoToTextBox("Other:" & data)
            UploadMessage(data, "Other")
        Catch ex As Exception
            AppendInfoToTextBox("OPC addScrew Err:" & ex.Message & ex.StackTrace)
        End Try
    End Sub

#End Region

#Region "读码及MES信息获取"

    ''' <summary>
    ''' ScanSNAndMESRequest
    ''' </summary>
    ''' <param name="SN"></param>
    ''' <remarks></remarks>
    Public Function ScanSNAndMESRequest(ByVal SN As String, ByVal Model As String) As Boolean
        Try
            If Can_Barcode = False Or SN = Input Then
                Return False
            End If
            AppendInfoToTextBox("接收SN信息：" + SN)
            SN = SN.ToUpper
            AppendInfoToTextBox("SN转换大写：" + SN)
            '''''''''判断是否是8S或者51类型条码
            'Dim snFlag = False
            'If SN(0) = "8" And SN(1) = "S" Then
            '    snFlag = True
            'ElseIf SN(0) = "5" And SN(1) = "1" Then
            '    snFlag = True
            'ElseIf SN(0) = "P" And SN(1) = "F" Then
            '    snFlag = True
            'End If
            Dim time As DateTime = DateTime.Now
            Dim curProd As New ProdInfo

            If machineInfo.DirSwitchProd = "1" Then
                AppendInfoToTextBox("SN:" & SN & "," & "Model:" & Model & "," & "Length:" & SN.Length)
                curProd.status = True
                curProd.sn = SN
                curProd.model_name = Model
                curProd.serial_number = SN
                Dim stime As String = Round((DateTime.Now.Ticks - time.Ticks) / 10000, 1) & "ms"
                AppendInfoToTextBox(SN & ":SN条码绑定OK:" & SN & ":机型名称" & curProd.model_name & stime + vbCrLf)
                If curProd.model_name = "" Then
                    AppendInfoToTextBox("接收产品等于空，赋值产品信息'PASS'")
                    curProd.model_name = "PASS"
                End If
                curProd.unlock_flag = True
                ProdInfoQueue.Enqueue(curProd)
                showSNQueueFlag = True
                Return True
            End If

            If SN.Length < 6 Or newset(0) = False Then 'newset(8)启用扫码切模板
                AppendInfoToTextBox("SN条码低于6位或未启用扫码功能")
                Return False
            End If

            If SN <> Input Then
                AppendInfoToTextBox("SN:" & SN & vbCrLf & "Length:" & SN.Length)
                Input = SN
                Dim SFData As String = MES_BaseDataRequest_OLD(SN) ''''接收MES回传信息
                AppendInfoToTextBox("接收MES回传Base信息：" & SFData)
                If SFData <> "" Then
                    curProd.status = getJsonKeyValue("status", SFData)
                    curProd.model_name = getJsonKeyValue("model_name", SFData)
                    curProd.serial_number = getJsonKeyValue("serial_number", SFData)
                    curProd.sn = curProd.serial_number
                    'curProd.keyParts_rfid = getJsonKeyValue("keyparts_rfid", SFData)

                    If curProd.status Then
                        Dim stime As String = Round((DateTime.Now.Ticks - time.Ticks) / 10000, 1) & "ms"
                        AppendInfoToTextBox(SN & "MES请求耗时:" & stime)
                        If Round((DateTime.Now.Ticks - time.Ticks) / 10000, 1) > 600 Then
                            AppendInfoToTextBox(SN & "MES请求时间大于600ms:" & stime)
                        End If
                        ProdInfoQueue.Enqueue(curProd)
                        If ProdInfoQueue.Count > 3 Then
                            AppendInfoToTextBox(ProdInfoQueue(0).sn & "缓存队列>3尝试清除首队列重新排序")
                            For i As Integer = 0 To ProdInfoQueue.Count - 1
                                AppendInfoToTextBox("打印当前所有队列" & ProdInfoQueue(i).sn)
                            Next
                            ProdInfoQueue.Dequeue()
                        End If
                        showSNQueueFlag = True
                        Return True
                    End If
                End If
            End If
        Catch ex As Exception
            AppendInfoToTextBox(ex.Message.ToString() & ex.StackTrace.ToString())
        End Try
        Return False
    End Function

    ''' <summary>
    ''' 展示SN队列的第一第二个元素
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ShowCurrentSNListQueue()
        Try
            CurrentSNList.Text = ""
            If ProdInfoQueue.Count > 0 Then
                AppendInfoToTextBox("当前队列个数 = " & ProdInfoQueue.Count)
                For i As Integer = 0 To ProdInfoQueue.Count - 1
                    Dim Str As String = ProdInfoQueue(i).sn & "," & ProdInfoQueue(i).model_name
                    CurrentSNList.AppendText(Str & vbCrLf)
                    AppendInfoToTextBox("队列:" & i & ":" & Str)
                Next
            Else
                AppendInfoToTextBox("当前队列个数 = 0")
            End If
        Catch ex As Exception
            AppendInfoToTextBox(ex.Message.ToString & ex.StackTrace.ToString)
        End Try
    End Sub

    ''' <summary>
    ''' 获取SN所对应的贴附组合列表
    ''' </summary>
    ''' <param name="SN"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function MES_BaseDataRequest(ByVal SN As String) As String
        Dim result As String = ""
        Dim SendData As String = ""
        Try
            SendData = "{""DATAIN"":""" & SN & """}"
            AppendInfoToTextBox("发送信息给MES：" & SendData)
            '
            If testMode = True Then
                result = TextBox_BaseInfo.Text
                AppendInfoToTextBox("测试模式MES Base数据：" & result)
            Else
                If newset(0) = False Then '’
                    '2,4,6,8
                    result = ""
                Else
                    MESheader(1, 1) = "GET_WIPSN_BASEINFO"
                    MESheader(3, 1) = Format(DateTime.Now, "yyyy-MM-dd HH:mm:ss")
                    result = MakeRequest2(machineInfo.IP, "", 10000, MESheader, SendData)
                End If
            End If
        Catch ex As Exception
            AppendInfoToTextBox(ex.Message.ToString & ex.StackTrace.ToString)
        End Try
        Return result
    End Function

    ''' <summary>
    ''' mes数据访问
    ''' </summary>
    ''' <param name="parameters"></param>
    ''' <param name="timeOut"></param>
    ''' <param name="header"></param>
    ''' <param name="PostData"></param>
    ''' <returns></returns>
    Public Function MakeRequest2(URL As String, parameters As String, timeOut As Integer, header(,) As String, PostData As String) As String
        Dim responseValue As String = String.Empty
        Try
            Dim request As HttpWebRequest = CType(WebRequest.Create(URL + parameters), HttpWebRequest)
            request.Method = HttpVerb.POST.ToString
            request.ContentLength = 0
            request.ContentType = "application/json"
            For i As Integer = 0 To header.GetLength(0) - 1
                request.Headers.Add(header(i, 0), header(i, 1))
            Next
            request.Timeout = timeOut
            If String.IsNullOrEmpty(PostData) = False Then
                Dim bytes() As Byte = Encoding.UTF8.GetBytes(PostData)
                request.ContentLength = bytes.Length
                Using writeStream As Stream = request.GetRequestStream()
                    writeStream.Write(bytes, 0, bytes.Length)
                End Using
            End If

            Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)

                If response.StatusCode <> HttpStatusCode.OK Then
                    Dim message As String = String.Format("Request failed. Received HTTP {0}", response.StatusCode)
                    AppendInfoToTextBox("MES访问异常：" & message)
                End If
                Using responseStream As Stream = response.GetResponseStream()
                    If responseStream IsNot Nothing Then
                        Using reader As StreamReader = New StreamReader(responseStream)
                            responseValue = reader.ReadToEnd()
                        End Using
                    End If
                End Using
            End Using
        Catch ex As Exception
            MsgBox(ex.Message)
            AppendInfoToTextBox(ex.Message)
            responseValue = ""
        End Try
        Return responseValue
    End Function

    ''' <summary>
    ''' 获取机型的旧接口
    ''' </summary>
    ''' <param name="SN"></param>
    ''' <returns></returns>
    Public Function MES_BaseDataRequest_OLD(ByVal SN As String) As String
        Dim result As String = ""
        Dim SendData As String = ""
        Try
            SendData = "{""DATAIN"":""" & SN & """}"
            AppendInfoToTextBox("发送信息给MES：" & SendData)
            '
            If testMode = True Then
                result = TextBox_BaseInfo.Text
                AppendInfoToTextBox("测试模式MES Base数据：" & result)
            Else
                If newset(0) = False Then '’
                    result = ""
                Else
                    MESheader(1, 1) = "GET_WIPSN_BASEINFO"
                    MESheader(3, 1) = Format(DateTime.Now, "yyyy-MM-dd HH:mm:ss")
                    result = MakeRequest2_OLD(machineInfo.IP_51, "", 500, MESheader, SendData)
                    If result = "" Then
                        AppendInfoToTextBox("MES Base数据为空,进行第二次访问")
                        result = MakeRequest2_OLD(machineInfo.IP_51, "", 500, MESheader, SendData)
                        If result = "" Then
                            AppendInfoToTextBox("第三次访问 MES Base数据为空，结束访问")
                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            AppendInfoToTextBox(ex.Message.ToString & ex.StackTrace.ToString)
        End Try
        Return result
    End Function

    Public Function MakeRequest2_OLD(URL As String, parameters As String, timeOut As Integer, header(,) As String, PostData As String) As String
        Dim responseValue As String = ""
        Try
            Dim request As HttpWebRequest = CType(WebRequest.Create(URL + parameters), HttpWebRequest)
            request.Method = HttpVerb.POST.ToString
            request.ContentLength = 0
            request.ContentType = "application/json"
            For i As Integer = 0 To header.GetLength(0) - 1
                request.Headers.Add(header(i, 0), header(i, 1))
            Next
            request.Timeout = timeOut
            If String.IsNullOrEmpty(PostData) = False Then
                Dim bytes() As Byte = Encoding.UTF8.GetBytes(PostData)
                request.ContentLength = bytes.Length
                Using writeStream As Stream = request.GetRequestStream()
                    writeStream.Write(bytes, 0, bytes.Length)
                End Using
            End If

            Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)

                If response.StatusCode <> HttpStatusCode.OK Then
                    Dim message As String = String.Format("Request failed. Received HTTP {0}", response.StatusCode)
                    AppendInfoToTextBox("MES访问异常：" & message)
                End If
                Using responseStream As Stream = response.GetResponseStream()
                    If responseStream IsNot Nothing Then
                        Using reader As StreamReader = New StreamReader(responseStream)
                            responseValue = reader.ReadToEnd()
                        End Using
                    End If
                End Using
            End Using
        Catch ex As Exception
            AppendInfoToTextBox(ex.Message.ToString & ex.StackTrace.ToString)
            responseValue = ""
        End Try
        Return responseValue
    End Function

    Private Function MES_BaseDataRequest51(ByVal SN As String) As String
        Dim result As String = ""
        Dim SendData As String = ""
        Try
            'SN = " http://10.159.45.217:8080/api/NB-PC-BOX/51J_CHANGE_SN?SUBSSN=" & SN
            Dim mes1 As MES51 = New MES51
            mes1.KPS = SN
            SendData = JsonHelper.ToJson(mes1)
            '"{\"name\":\"王小宝\",\"age\":30,\"son\":[{\"name\":\"李大牛\",\"age\":10}]}"
            AppendInfoToTextBox("发送信息给获取SN：" & SN)
            '
            If testMode = True Then
                result = TextBox_BaseInfo.Text
                AppendInfoToTextBox("测试模式MES Base数据：" & result)
            Else
                If newset(0) = False Then '’
                    result = ""
                Else
                    MESheader(1, 1) = "GET_SN_BYKPS" '"GET_WIPSN_BASEINFO"
                    MESheader(2, 1) = "OGGID"
                    MESheader(3, 1) = Format(DateTime.Now, "yyyy-MM-dd HH:mm:ss")
                    'mesapi.lcfuturecenter.com:9000/api/gateway
                    'result = MakeRequest3("http://10.159.45.217:8080/api/NB-PC-BOX/51J_CHANGE_SN?SUBSSN=" & SN, "", 10000, MESheader, SN)

                    result = MakeRequest3(machineInfo.IP_51, "", 10000, MESheader, SendData)
                    AppendInfoToTextBox("result:" & result)
                End If
            End If
        Catch ex As Exception
            AppendInfoToTextBox(ex.Message.ToString & ex.StackTrace.ToString)
        End Try
        Return result
    End Function

    Private Sub Button_ClearSNQueue_Click(sender As Object, e As EventArgs) Handles Button_ClearSNQueue.Click
        Try
            If MsgBox("是否清空扫码队列？", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                ProdInfoQueue.Clear()
                Input = ""
                ' ShowCurrentSNListQueue()
                showSNQueueFlag = True
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub ManualInput_KeyDown(sender As Object, e As KeyEventArgs) Handles ManualInput.KeyDown
        Try
            If e.KeyCode = Keys.Enter Then

                ScanSNAndMESRequest(ManualInput.Text, "")
                ManualInput.Text = ""
            End If
        Catch ex As Exception

        End Try
    End Sub

#End Region

    Dim testMode As Boolean = False

    Private Sub Button_TestMode_Click(sender As Object, e As EventArgs) Handles Button_TestMode.Click
        Try
            If testMode = True Then
                testMode = False
                Button_TestMode.BackColor = Color.WhiteSmoke
                Button_TestMode.Text = "开启测试模式"
            Else
                testMode = True
                Button_TestMode.BackColor = Color.Red
                Button_TestMode.Text = "测试模式中"
            End If
        Catch ex As Exception

        End Try
    End Sub

    Dim backHourMaintance As Integer = DateTime.Now.Hour
    Dim delLog As Integer
    Dim IOTsendNO As Integer = 0

    Private Sub TimerOPC_Tick(sender As Object, e As EventArgs) Handles TimerOPC.Tick
        TimerOPC.Enabled = False
        Try
            If newset(7) Then 'IOT 数据上传
                'OPC_Refresh_Alarm()
                'OPC_RefreshData_Sensor()
                'OPC_Refresh_ProductionLog()
                'OPC_RefreshData_Parameter()
                'OPC_RefreshData_Info()
                If Now.Hour = backHourMaintance Then '每小时更新一次
                    backHourMaintance += 1
                    If backHourMaintance = 24 Then
                        backHourMaintance = 1
                    End If
                    OPC_Refresh_Maintance()
                    wait(50)
                    IOTsendNO = 2
                End If

                Select Case IOTsendNO
                    Case 0
                        wait(50)
                        OPC_RefreshData_ProductionData()
                    Case 1
                        wait(50)
                        OPC_RefreshData_Status()
                End Select
                IOTsendNO += 1

                If IOTsendNO > 1 Then
                    IOTsendNO = 0
                End If

            End If

            '删除log文件
            If delLog = 0 And Now.Hour = 8 Then
                delLog = 1
                DeleteDir(30)
            Else
                If Now.Hour <> 8 Then
                    delLog = 0
                End If
            End If
        Catch ex As Exception

        End Try
        TimerOPC.Enabled = True
    End Sub

    ''' <summary>
    ''' 删除日志文件
    ''' </summary>
    ''' <param name="Days"></param>
    Private Sub DeleteDir(ByVal Days As Integer)
        Dim Path As String = CD_Dir & "上位机资料\log\"

        Dim MDocumentPath As String = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\"
        Dim MDesktopPath As String = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) & "\"
        Try
            Dim FileExits As New DirectoryInfo(Path)
            If FileExits.Exists Then
                If Path.Length > 3 Then
                    If Path = MDocumentPath Or Path = MDesktopPath Then
                        AppendInfoToTextBox("清理警告：当前路径可能清理到系统文件，请重新设置并确定存储路径的安全性。")
                    Else
                        Dim FileList() As String = Directory.GetDirectories(Path)
                        If FileList.Length > Days Then
                            For i As Integer = 1 To FileList.Length - Days
                                Directory.Delete(FileList(i - 1), True)
                            Next
                            AppendInfoToTextBox("清理成功:" & "路径{" & Path & "}的文件已删除。")
                        End If
                    End If
                End If
            Else
                AppendInfoToTextBox("清理警告：当前路径可能清理到系统文件，请重新设置并确定存储路径的安全性。")
            End If
        Catch ex As Exception
            AppendInfoToTextBox(ex.Message.ToString() & ex.StackTrace.ToString())
        End Try

    End Sub

    ''' <summary>
    ''' 加螺丝
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub Button_addScrew_Click(sender As Object, e As EventArgs) Handles Button_addScrew.Click
        Try
            FrmAddScrew.ShowDialog()
        Catch ex As Exception

        End Try
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If DateTimePicker6.Value > DateTimePicker5.Value Then
            MsgBox("查询开始时间大于结束时间！")
        Else
            Dim sql As String = "select * from errorinfo where 日期 >=" & "'" & Format(DateTimePicker6.Value, "yyyy-MM-dd HH:mm:ss") & "'" & "and " & "日期 <=" & "'" & Format(DateTimePicker5.Value, "yyyy-MM-dd HH:mm:ss") & "'"
            Dim ds As DataSet = SearchMysql(sql)
            DataGridView1.DataSource = ds.Tables(0)
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            Dim sql As String = "select * from errorinfo"
            Dim ds As DataSet = SearchMysql(sql)
            DataGridView1.DataSource = ds.Tables(0)
        Catch ex As Exception
            AppendInfoToTextBox("LoadAccess1:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
        If TabControl1.SelectedIndex = 1 Then
            If machineInfo.ConfigMustLogin = "1" Then
                Panel1.Enabled = False
                Dim result As DialogResult = FrmUserPad.ShowDialog()
                If result = DialogResult.Cancel Then
                    Return
                End If
                If G_AdminPwd = "" Then
                    Return
                End If
                If G_AdminPwd <> "123" Then
                    MsgBox("密码错误")
                    Return
                End If
                If gPriority = 1 Then
                    Panel1.Enabled = True
                End If
            Else
                If gPriority = 1 Then
                    Panel1.Enabled = True
                End If
            End If

        End If
    End Sub

    Public MouseMove_X As Integer
    Public MouseMove_Y As Integer
    Public MouseMove2_X As Integer
    Public MouseMove2_Y As Integer

    Private Sub Timer_SMSB_Tick(sender As Object, e As EventArgs) Handles Timer_SMSB.Tick
        MouseMove_X = System.Windows.Forms.Cursor.Position.X
        MouseMove_Y = System.Windows.Forms.Cursor.Position.Y
        If gPriority = 0 Then
            TextBox_OPID.Text = "未登录"
            TextBox_OPID.BackColor = Color.WhiteSmoke
            FrmAdmin.EnableMenu()
        End If
    End Sub

    ''' <summary>
    ''' 自动退出登录
    ''' </summary>
    Private Sub Automaticlogout()
        Dim num As Integer = 0
        While True
            MouseMove2_X = System.Windows.Forms.Cursor.Position.X
            MouseMove2_Y = System.Windows.Forms.Cursor.Position.Y
            If gPriority <> 0 Then
                If MouseMove_X = MouseMove2_X And MouseMove_Y = MouseMove2_Y Then
                    Thread.Sleep(1000)
                    num += 1
                    If num >= 30 Then
                        num = 0
                        AppendInfoToTextBox("达到设定时间，自动退出登录")
                        gPriority = 0
                    End If
                End If
            End If
            Thread.Sleep(500)
        End While
    End Sub

    Private Sub 读码设置ToolStripMenuItem_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub ClearAllQuene()
        AppendInfoToTextBox("清空所有队列")
        ProdInfoQueue.Clear()
        showSNQueueFlag = True
    End Sub

    Private Sub TxtBlowNum_KeyDown(sender As Object, e As KeyEventArgs) Handles TxtBlowNum.KeyDown
        If e.KeyCode = Keys.Enter Then
            Todaycount.ScrewFailed35 = 0
            TxtBlowNum.Text = Todaycount.ScrewFailed35
        End If
    End Sub

End Class